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);
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?
Nice after I made my bounty I found a really good site that explains how to use .data() to expose plubic properties and methods.
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);