I'm writing a test in Mocha / Node js and want to use a setTimeout to wait for a period before executing a block of code.
How can I accomplish this?
It appears that within a Mocha test case, setTimeout() does not work. (I am aware that you can setTimeout per test case and per test file, that's not what I need here.)
In a js file run with Node, ie, node miniTest.js
, this will wait 3 seconds, then print the line inside the setTimeout function.
miniTest.js
console.log('waiting 3 seconds...');
setTimeout(function() {
console.log('waiting over.');
}, 3000);
In a js file run with Mocha, ie, mocha smallTest.js
, this will not wait, and will finish executing and exit without ever printing the line inside the setTimeout function.
smallTest.js:
mocha = require('mocha');
describe('small test', function() {
it('tiny test case', function() {
console.log('waiting 3 seconds...');
setTimeout(function () {
console.log('waiting over.')
}, 3000);
});
});
This is a complete example. You need to call done() in every assertion you make. You can leave out the before function and do the setTimeout in one of your it functions, but it should still use and call done() after assert.
You need to have done passed as a parameter in your test which will be invoked once the test passes.
You can write your test like
});
This will wait 3 seconds after that it will print 'waiting over' and pass the test. You can also have a condition inside the timeout depending upon whether the condition is satisfied or not you can pass the test by calling
or fail the test by either throwing an error or passing the error message in
Have your test function take a parameter (typically called
done
). Mocha will pass a function that you'll call in thesetTimeout
function (e.g. afterconsole.log
calldone()
).See https://mochajs.org/#asynchronous-code.
You are forgetting to pass parameter in
it('tiny test case', function()
and call done() after console.log in setTimeout method.