To begin with, Mocha is set up to read a specific file called test/mocha.opts
, which can include various command line arguments. You have the option of creating this file and inserting the following:
--timeout 5000
Each time you execute Mocha from the command line, it will refer to this file and establish a default timeout setting of 5 seconds.
Alternatively, another approach that might be more suitable for your particular scenario is to define the timeout within a top-level describe
function in your test file like so:
describe("something", function () {
this.timeout(5000);
// tests...
});
This method permits you to specify a timeout on a per-file basis.
You could utilize both techniques if you prefer a universal default of 5000 but need different settings for certain files.
It should be noted that using an arrow function to call this.timeout
(or access any other property of this
defined by Mocha) is generally not viable. For example, the following will typically fail:
describe("something", () => {
this.timeout(5000); //will not work
// Tests...
});
The reason behind this issue is that an arrow function captures the this
keyword from its surrounding context. Although Mocha supplies the function with the appropriate value for this
, this value does not get passed into the arrow function itself. According to the Mocha documentation found here:
Utilizing arrow functions ("lambdas") with Mocha is discouraged due to their inability to interact with the Mocha context as a result of lexical binding of this.