I have following question if we have unit test file my-spec.js and running with mocha :
mocha my-spec.js
default timeout will be 2000 ms.It can overwritten for partial test with command line parameter :
mocha my-spec.js --timeout 5000
The question is: Is there possible to change default timeout globally for all tests ? I.e when you call
mocha my-spec.js
the default timeout value to be different from 2000 ms Thanks in advance
By default Mocha will read a file named
test/mocha.opts
that can contain command line arguments. So you could create such a file that contains:Whenever you run Mocha at the command line, it will read this file and set a timeout of 5 seconds by default.
Another way which may be better depending on your situation is to set it like this in a top level
describe
call in your test file:This would allow you to set a timeout only on a per-file basis.
You could use both methods if you want a global default of 5000 but set something different for some files.
Note that you cannot generally use an arrow function if you are going to call
this.timeout
(or access any other member ofthis
that Mocha sets for you). For instance, this will usually not work:This is because an arrow function takes
this
from the scope the function appears in. Mocha will call the function with a good value forthis
but that value is not passed inside the arrow function. The documentation for Mocha says on this topic:If you happen (like me) to be running Mocha in a browser rather than on the server, you can always change the global configuration using
mocha.setup
.Just add the line above anywhere in your test suite, preferably at the top of your spec or in a separate test helper.
Here is the link to the documentation with a few examples showing how to configure Mocha in the browser.
Adding this for completeness. If you (like me) use a script in your
package.json
file, just add the--timeout
option to mocha:Then you can run
npm run test
to run your test suite with the timeout set to 10,000 milliseconds.Just adding to the correct answer you can set the timeout with the arrow function like this: