Created
April 4, 2013 21:20
-
-
Save jasonrhodes/5314470 to your computer and use it in GitHub Desktop.
One way to build a unit-testable jQuery plugin.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | |
| }); |
Author
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
With this method, you can only test methods in myWidgetCreator that don't use
this, but any methods that usethisshould be tested via the plugin itself. Something likeCreator.doSomethingcould be unit tested using this method, though.