Change default timeout for mocha

2019-01-10 18:16发布

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

4条回答
Evening l夕情丶
2楼-- · 2019-01-10 18:26

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:

--timeout 5000

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:

describe("something", function () {
    this.timeout(5000);

    // tests...
});

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 of this that Mocha sets for you). For instance, this will usually not work:

describe("something", () => {
    this.timeout(5000);

    // tests...
});

This is because an arrow function takes this from the scope the function appears in. Mocha will call the function with a good value for this but that value is not passed inside the arrow function. The documentation for Mocha says on this topic:

Passing arrow functions (“lambdas”) to Mocha is discouraged. Due to the lexical binding of this, such functions are unable to access the Mocha context.

查看更多
Emotional °昔
3楼-- · 2019-01-10 18:29

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.

mocha.setup({ timeout: 5000 });

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.

查看更多
别忘想泡老子
4楼-- · 2019-01-10 18:33

Adding this for completeness. If you (like me) use a script in your package.json file, just add the --timeout option to mocha:

"scripts": {
  "test": "mocha 'test/**/*.js' --timeout 10000",
  "test-debug": "mocha --debug 'test/**/*.js' --timeout 10000"
},

Then you can run npm run test to run your test suite with the timeout set to 10,000 milliseconds.

查看更多
聊天终结者
5楼-- · 2019-01-10 18:51

Just adding to the correct answer you can set the timeout with the arrow function like this:

it('Some test', () => {

}).timeout(5000)
查看更多
登录 后发表回答