Somehow I'm not able to write Mocha JS test for a relatively very simple function. The JavaScript Source file looks like this
exports.cb = function() {
console.log("The function is called after 3 seconds");
}
exports.testfn = function(cb) {
setTimeout(cb, 3000);
}
And the test code is written as
describe('Main Test', function(){
it('A callback Tests', function(done){
asn.testfn(asn.cb);
done();
});
});
I'm encountering 2 problems.
- The test code ends immediately with done()
- If I don't call done(), then the function is called but tests fails because it expected to call done() for async functions
I've looked into documentations but not sure how this can be done.
I can write tests using promises and it works fine. But for the scenarios where we need to use setTimeout, how shall it be done?
Assuming what you're trying to test is
testfn, you wouldn't usecb, you'd use a callback in the test; see comments:If you want to call
asn.cbfor some reason, you'd do it in the anonymous function above, but if you want to testasn.cb, you should do that serparately from testingasn.testfn.