2017-03-01 57 views
2

我想创建一个与BDD(行为驱动开发)的jQuery模块。应该jquery组件返回false

这里是我的组件

(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); 

这里是我的测试

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"); 
}); 

HERE IS FIDDLE

我有2个问题。

1-如果我的组件返回布尔值,该怎么办?它是错误的模式?

2-如何我可以从我的组件

回答

1

那是因为你没有返回new MyModule返回布尔,你回来的this.each返回的值是一个jQuery对象。如果你想要一个布尔值,你必须返回一个布尔值。就像这样:

$.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) 
}; 

从回调中返回是不影响父函数的返回值。

+0

所以验证应该在$ .fn.myModule内 –

+0

@MehmetErenYener是的,你应该积累所有'新的MyModule'调用的结果,然后返回该值。 –