Introduction
Mocha is a powerful JavaScript test framework that runs on Node.js and in the browser, making asynchronous testing easy and enjoyable. Mocha tests execute in sequential order, allowing for flexible and accurate reporting and mapping uncaught exceptions to the appropriate test cases. Tests that are executed have some duration and timeouts. We will learn about it in detail through this article. Let’s dive in.
Timeouts
Any test that takes longer than 2 seconds (2000ms) to complete will be timed out by Mocha.js by default. A timeout causes the test to fail and a timeout error to be thrown.
For a given test suite, hook, or test case, Mocha.js provides a this.timeout() method for specifying the amount of time that should elapse before a timeout occurs. The time in milliseconds is represented by the number passed to this.timeout().
The timeout can be configured in various ways (suite, hook, and test levels).
Suite-level
Can we use this to apply suite-level timeouts to the entire test? suites? or to disable them. timeout(0). All nested suites and test cases that do not override the value inherit this timeout setting.
describe('a suite of tests', function() {
this.timeout(500);
it('This process should take less than 500 milliseconds', function(done) {
setTimeout(done, 300);
});
it('This process should take less than 500 milliseconds as well', function(done) {
setTimeout(done, 250);
});
});
Test-level
A test-case can have test-specific timeouts applied to it. You can also use this.timeout(0) to completely disable timeouts:
it('This process has to take less than 500ms', function(done) {
this.timeout(500);
setTimeout(done, 300);
});
Hook-level
Hook-level timeouts can also be applied to a test-case, as shown in the examples below:
describe('a suite of tests', function() {
beforeEach(function(done) {
this.timeout(3000); // This is a very long environment setup.
setTimeout(done, 2500);
});
});
describe('a suite of tests', function() {
afterEach(function(done) {
this.timeout(70); // The test duration here is within normal range.
setTimeout(done, 65);
});
});
describe('a suite of tests', function() {
beforeEach(function(done) {
this.timeout(30); // A very fast environment setup.
setTimeout(done, 25);
});
});
This can be used in the same way as the other types of timeout tests. timeout(0) disables the hook's timeout.




