Skip to content

Instantly share code, notes, and snippets.

@jasonrhodes
Created April 4, 2013 21:20
Show Gist options
  • Select an option

  • Save jasonrhodes/5314470 to your computer and use it in GitHub Desktop.

Select an option

Save jasonrhodes/5314470 to your computer and use it in GitHub Desktop.
One way to build a unit-testable jQuery plugin.
var myWidgetCreator = (function ($, lib) {
var Creator = {};
Creator.create = function (args) {
// 'this' is the captured jQuery object
// because we called 'apply' from the widget
this.html(Creator.doSomething());
};
Creator.doSomething = function () {
return "WIETERS";
};
return Creator;
})(jQuery, {});
jQuery.fn.myWidget = function (options) {
myWidgetCreator.create.apply(this, options);
};
jQuery(document).ready(function ($) {
$("body").myWidget();
});
@jasonrhodes
Copy link
Copy Markdown
Author

With this method, you can only test methods in myWidgetCreator that don't use this, but any methods that use this should be tested via the plugin itself. Something like Creator.doSomething could be unit tested using this method, though.

@jasonrhodes
Copy link
Copy Markdown
Author

Actually, now that I think about it... you can test any of the methods that use 'this' and assume it to be a jQuery object just by passing it a dummy jQuery object like so:

myWidgetCreator.create.apply($("<div>"), options);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment