我在编写 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/