JQuery plugin: how to check my plugin configuration using qunit?

I am trying to execute qunit while writing a jQuery plugin, and I was wondering how I can verify 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 can I expose internal methods / members from my plugin inside my tests?

+3
source share
1 answer

After I made my award, I found a good site that explains how to use .data () to expose plural properties and methods.

Here you can find the entire blog post: object oriented object 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 data
           element.data('myplugin', myplugin);
       });
   };
})(jQuery);
+5

Source: https://habr.com/ru/post/1776803/


All Articles