I googled on how to unit test but examples are so simple. the examples always show functions that return something or do ajax that returns something – but never have i seen examples that do callbacks, nested callbacks and functions that are “one-way”, that they just store something and never return anything.
say i have a code like this, how should i go about testing it?
(function(){
var cache = {};
function dependencyLoader(dependencies,callback2){
//loads a script to the page, and notes it in the cache
if(allLoaded){
callback2()
}
}
function moduleLoader(dependencies, callback1){
dependencyLoader(dependencies,function(){
//do some setup
callback1()
});
}
window.framework = {
moduleLoader : moduleLoader
}
}());
framework.moduleLoader(['foo','bar','baz'],function(){
//call when all is loaded
})
This illustrates a problem with keeping things private in an anonymous function in javascript. It’s a bit difficult to validate that things are working internally.
If this was done test first then the cache, dependencyLoader and moduleLoader should be publicly available on the framework object. Or else it would be difficult to validate that the cache was handled properly.
To get things going I’d recommend you take a gander on BDD, that conveniently gives you an approach to help you start by letting you spell out the behaviour with a
given-when-thenconvention. I like to use Jasmine, which is a javascript BDD framework (that integrates withjstestdriver), for this kind of thing and the unit tests I’d make for the sample you have above would be:Hope these tests are self explanatory. I tend to rewrite the tests so that they nest nicely, and usually the actual calls are done in the
beforeEachfunctions while the validation are done in theitfunctions.