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

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

问题描述

如果我们有一个单元测试文件 my-spec.js 并使用 mocha 运行:

If we have a unit test file my-spec.js and running with mocha:

mocha my-spec.js

默认超时时间为 2000 毫秒.可以使用命令行参数覆盖部分测试:

The default timeout will be 2000 ms. It can be overwritten for partial test with a command line parameter:

mocha my-spec.js --timeout 5000

是否可以全局更改所有测试的默认超时?即当您调用时,默认超时值将与 2000 毫秒不同:

Is it possible to change the default timeout globally for all tests? i.e. the default timeout value will be different from 2000 ms when you call:

mocha my-spec.js

推荐答案

默认情况下,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 为您设置的 this 的任何其他成员),通常不能使用箭头函数.例如,这通常不起作用:

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); //will not work

    // tests...
});

这是因为箭头函数从函数出现的作用域中获取this.Mocha 将调用带有this 值的函数,但不会传递该值在箭头函数里面.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.由于 this 的词法绑定,此类函数无法访问 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天全站免登陆