how to unit test internal functions in jquery plugin?
in a jQuery plugin i have created helper functions, like this
(function($) {
var someHelperFunction = function(s, d) {
return s*d;
}
var someOtherHelperFunction = function(s) {
return s*2;
}
// here goes the normal开发者_如何学编程 plugin code
})(jQuery);
now I want to call someHelperFunction from the outside, to be able to unit test it, is that possible somehow?
Per this related question, I'd say just test the external interface.
But if you must test these methods in isolation, you'll have to test "copies" of them outside of the context of their deployment as internal methods. In other words, create an object in which they are not inaccessible to client code, and then cobble those versions together with your outer script in a pre-process. Sounds like a lot of work, but hey, that's the point of hiding methods, right? (To make them unreachable.)
If the internal functions need testing that's a good indicator that they should maybe be in a separate module somewhere and injected as dependencies and used within your objects public interface implementation. That's the more "testable" way to do it.
var myActualImplementationTestTheHellOutOfMe = function(s, d) {
return s*d;
}
(function($, helper) {
var someHelperFunction = function(s, d) {
return helper(s, d);
}
var someOtherHelperFunction = function(s) {
return s*2;
}
// here goes the normal plugin code
})(jQuery, myActualImplementationTestTheHellOutOfMe);
You may also like to consider JavaScript doctests. There are two implementations of which I'm aware: Ian Bicking's doctest.js, and my own doctest.
the helpers are scoped inside the plugin, which is an anonymous function , and you cannot access the variables declared inside it.
If you want to test it, drop the var
keyword in front of the functions. That will declare the functions as global (will attach them to the window object), giving them the ability to be visible from the window scope ( by calling someHelperFunction
or window.someHelperFunction
).
so, for testing :
(function($) {
someHelperFunction = function(s, d) {
return s*d;
}
someOtherHelperFunction = function(s) {
return s*2;
}
// here goes the normal plugin code
})(jQuery);
after the testing is over, add the var
keyword again.
Update
I think that a better approach would be to group your testable functions in an object - and construct an api. Then, on the same principle, you could make that api visible in the global scope or not:
(function($, global) {
someHelperFunction = function(s, d) {
return s*d;
}
someOtherHelperFunction = function(s) {
return s*2;
}
var api = {
someHelperFunction: someHelperFunction,
someOtherHelperFunction: someOtherHelperFunction
};
// decide whether you want to expose your api or not
if(makeGlobal) {
global.api = api;
}
})(jQuery, this);
take a look at qunit, a JavaScript unit test lib
精彩评论