jQuery插件:如何使用qunit测试插件的配置? [英] jQuery Plugin: How do I test the configuration of my plugin with qunit?

查看:90
本文介绍了jQuery插件:如何使用qunit测试插件的配置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying out qunit while writing a jQuery plugin and I was wondering how I can test the following:

(function($){

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

        options = $.extend(defaults, options);

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

})(jQuery);

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

This is a simple version of my qunit test:

module('MyPlugin: Configuration');

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

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

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

So I was wondering how I could expose internal methods/members from my plugin inside my tests?

推荐答案

很不错,当我获得赏金后,我发现了一个非常不错的网站,该网站解释了如何使用.data()公开润滑性和方法.

Nice after I made my bounty I found a really good site that explains how to use .data() to expose plubic properties and methods.

在这里您可以找到整个博客文章:构建面向对象的jquery插件.

Here you can find the whole blog post: building object oriented jquery plugin.

这是上面链接的完整示例,因此所有版权归博客文章的作者所有.

This is whole example from the above link so all credits go to the author of the blog post.

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

这篇关于jQuery插件:如何使用qunit测试插件的配置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆