Reputation: 16430
What are the shortcomings of javascript's revealing module pattern when unit testing with Jasmine?
And what are the potential workarounds?
Upvotes: 0
Views: 1046
Reputation: 4906
Basically the main caveat when you want to unit test a module (regardless of the test runner that is used) is the scope of the inner functions. That is, the inner methods; or if you will the private methods; are not accessible from outside of the module. Hence, it is not very obvious how to unit test those methods; This, of course, applies only in the case that you want to unit test your private methods.
I have written a blog post where this issue is described and a solution is proposed.
http://tech.pro/blog/1792/how-to-unit-test-private-functions-in-the-revealing-module-pattern
Upvotes: 1
Reputation: 110972
I'm using requireJS, which is a special kind of the module pattern, for over year now and cant see any shortcomings. Your module should use dependency injection so you can replace the dependencies of the module with mocks in your test.
var myModule = (function(dep1){
function someFancyAlgorythm(a){return a +1}
return {
foo: function(a){
dep1(someFancyAlgorythm(a))
}
}
})(dep1)
in your test
describe('myModule',function(){
var dep1;
var module;
beforeEach(function(){
dep1 = jasmine.createSpy();
module = myModule(dep1)
})
it('make crazy stuff', function(){
module.foo(1);
expect(dep1).toHaveBeenCalledWith(2);
})
})
Upvotes: 4
Reputation: 4144
Could try this way
var module = (function() {
var priv = function(){
};
var pub = function(){
};
/**start-private-test**/
pub._priv = priv ;
/**end-private-test**/
return {
pub : pub
}
}();
write test for pub._priv
and production remove code unit private-test
. for more information read this blog post
Upvotes: 1