代码之家  ›  专栏  ›  技术社区  ›  Pickels

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

  •  3
  • Pickels  · 技术社区  · 14 年前

    我在编写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');
    });
    

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

    1 回复  |  直到 14 年前
        1
  •  5
  •   Pickels    14 年前

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

    在这里您可以找到整个博客文章: 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);