I am trying to create a jquery module with BDD(Behavior-driven development).
Here is my component
(function($) {
function MyModule(element){
return false;
}
$.fn.myModule = function() {
var args = Array.prototype.slice.call(arguments, 1);
return this.each(function() {
new MyModule(this);
});
};
$.fn.myModule.Constructor = MyModule;
})(window.jQuery);
Here is my test
QUnit.test( "test", function( assert ) {
assert.expect(1);
var smallBox = $('<div/>',{'id':'smallBox'}).width(200).height(200);
var result = smallBox.myModule();
console.log(result); // This gives the HTML element itself but I am expecting it must be boolean false
assert.notOk(result, "should return false" );
});
I have 2 questions.
1- What if my component returns boolean. Is it wrong pattern?
2- How I can return boolean from my component
That is because you're not returning new MyModule
, you're returning the returned value of this.each
which is a jQuery object. If you want a boolean you'll have to return a boolean. Like this:
$.fn.myModule = function() {
var args = Array.prototype.slice.call(arguments, 1);
this.each(function() { // don't return here because then you'll return a jQuery object
new MyModule(this);
});
return false; // return a boolean (works)
};
Returning from inside the callback is not affecting the returned value of the parent function.