更改mocha的默认超时 [英] Change default timeout for mocha

查看:1817
本文介绍了更改mocha的默认超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有单位测试文件my-spec.js并使用mocha运行,我有以下问题

I have following question if we have unit test file my-spec.js and running with mocha :

mocha my-spec.js

默认超时时间为2000 ms。可以覆盖部分测试命令行参数:

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

默认超时值与2000毫秒不同
提前致谢

the default timeout value to be different from 2000 ms Thanks in advance

推荐答案

默认情况下,Mocha将读取一个名为 test / mocha.opts 的文件,该文件可以包含命令行参数。所以你可以创建一个包含以下内容的文件:

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

每当您在命令行运行Mocha时,它将读取此文件并默认设置为5秒的超时。

Whenever you run Mocha at the command line, it will read this file and set a timeout of 5 seconds by default.

根据您的具体情况,另一种可能更好的方法是在测试文件的顶级 describe 调用中将其设置为:

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.

如果你想要全局默认值5000但是为某些文件设置不同的东西,你可以使用这两种方法。

You could use both methods if you want a global default of 5000 but set something different for some files.

请注意,如果要打电话给 this.timeout (或访问 Mocha为你设定的这个)。例如,通常不起作用

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...
});

这是因为箭头函数需要这个从函数出现的范围.Mocha将为这个调用具有良好值的函数,但该值不会在箭头函数内传递。 Mocha的文档在此主题中说明:

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:

不鼓励将箭头函数(lambdas)传递给Mocha。由于它的词汇绑定,这些函数无法访问Mocha上下文。

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

这篇关于更改mocha的默认超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆