javascript - jQuery 插件 : How do I test the configuration of my plugin with qunit?

标签 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);

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

module('MyPlugin: Configuration');

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

    //equals(notsure.myPlugin({ foo: mockFoo }, 'no bar', 'Overwriting failed');
});

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

最佳答案

很高兴,在我悬赏之后,我发现了一个非常好的网站,它解释了如何使用 .data() 公开公共(public)属性和方法。

在这里您可以找到完整的博文:building object oriented jquery plugin .

这是来自上述链接的完整示例,因此所有学分归于博客文章的作者。

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

关于javascript - jQuery 插件 : How do I test the configuration of my plugin with qunit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4272916/

相关文章:

php - 使用网络应用程序打印 pdf

javascript - React Native Reanimated Carousel ScrollTo 事件不起作用

javascript - 如何选择二维数组表示的所有复选框?

jquery - 重新定位 Jquery UI 自动完成结果框

javascript - Knockout JS,如何在更改可观察数组中的值时更改样式属性

javascript - 什么可能导致 Angular 无法正常渲染?

javascript - 从下拉列表中选择选项

javascript - 每 10 秒重新加载一次 javascript 代码

jQuery 内容切换和淡入淡出插件?

javascript - 内容宽度未知的 jCarousel