jQuery插件:如何使用qunit测试插件的配置?

Pic*_*els 3 javascript jquery jquery-plugins qunit

我在编写jQuery插件时尝试qunit,我想知道如何测试以下内容:

(function($){

    $.fn.myPlugin = function(options){
        var defaults = {
            foo: function(){
                return 'bar';
            }
        };

        options = $.extend(defaults, options);

        return this.each(function(){ ... });
    };

})(jQuery);
Run Code Online (Sandbox Code Playgroud)

这是我的qunit测试的简单版本:

module('MyPlugin: Configuration');

test('Can overwrite foo', function(){
    var mockFoo = function(){ 
        return 'no bar';
    };

    //equals(notsure.myPlugin({ foo: mockFoo }, 'no bar', 'Overwriting failed');
});
Run Code Online (Sandbox Code Playgroud)

所以我想知道如何在我的测试中从我的插件中公开内部方法/成员?

Pic*_*els 5

在我获得赏金后很高兴我发现了一个非常好的网站,解释了如何使用.data()来暴露丰富的属性和方法.

在这里你可以找到整篇博文:构建面向对象的jquery插件.

这是来自上述链接的完整示例,因此所有信用都归到博客文章的作者.

(function($){
   var MyPlugin = function(element, options)
   {
       var elem = $(element);
       var obj = this;
       var settings = $.extend({
           param: 'defaultValue'
       }, options || {});

       // Public method - can be called from client code
       this.publicMethod = function()
       {
           console.log('public method called!');
       };

       // Private method - can only be called from within this object
       var privateMethod = function()
       {
           console.log('private method called!');
       };
   };

   $.fn.myplugin = function(options)
   {
       return this.each(function()
       {
           var element = $(this);

           // Return early if this element already has a plugin instance
           if (element.data('myplugin')) return;

           // pass options to plugin constructor
           var myplugin = new MyPlugin(this, options);

           // Store plugin object in this element's data
           element.data('myplugin', myplugin);
       });
   };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)