javascript - How can I test unit test my jQuery-based code? -


i have following code in file named index.js. want test functions in add, print being prime one.

(function($){   "use strict";    $(function(){      var add = function(a, b){     // ...       },     print = function(str){     // ...       },       setup = function(){     // ...       },       init = function(){     // ...       };        setup();       init();   }); })(jquery); 

how can so? way of coding add security on client side? have code runs on client side. no server involvement what-so-ever.

i tried :

var outerobj = (function(greet){     var innerobj = (function(){         return {test: function(){ console.log(greet); }}     })();     return innerobj; })("hi");  outerobj.test(); 

but, in case, innerobj line has $ on right hand of equal sign, making console yell error shouts $(...) not function. agree, it's array of single document object.

check out var = (function(){ var val = $(function(){return 10;})(); })(); in jquery enabled web-page's console, error.

even if ditch outer shell , bring $(function() {}); out. how gonna test that?

it's still object, still error.

what kind of testing can perform, unit, bdd, etc. , how?

i don't quite see pattern you're using here - seems bit of anti-pattern. it's not testable, , doesn't expose behaviour real world use. i'd highly recommend reading (or @ least skimming) javascript design patterns addy osmani, available free.

for unit testing, i've found happy midpoint between simple constructor pattern , revealing module pattern easiest work with.

var x = function($){ "use strict";    var add = function(a, b){      alert('add');     },     print = function(str){      return 1;     },     setup = function(){       alert('setup');     },     init = function(){       alert('init');     };    init();   setup();    return {       add: add,       print: print   }; };  var y = new x(jquery); 

in above example, y have add , print methods available. check out sample test on this fiddle.

as side note, i've been using excellent qunit framework setting , running js unit tests. it's jquery team, know it's gonna ;). i'd suggest checking out blanketjs reporting on coverage, , qunit-parameterize setting multiple test cases.

for worth, bdd isn't 'test type', way of working. tests should have - unit tests , integration tests important 2, imo. use qunit unit tests, , selenium nunit integration testing.


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -