如何在Mocha中增加单个测试用例的超时

本文翻译自:How to increase timeout for a single test case in mocha

I'm submitting a network request in a test case, but this sometimes takes longer than 2 seconds (the default timeout). 我正在测试用例中提交网络请求,但这有时会花费2秒钟以上的时间(默认超时)。

How do I increase the timeout for a single test case? 如何增加单个测试用例的超时时间?


#1楼

参考:https://stackoom.com/question/150pT/如何在Mocha中增加单个测试用例的超时


#2楼

Here you go: http://mochajs.org/#test-level 您可以在这里: http : //mochajs.org/#test-level

it('accesses the network', function(done){
  this.timeout(500);
  [Put network code here, with done() in the callback]
})

For arrow function use as follows: 对于箭头功能,使用如下:

it('accesses the network', (done) => {
  [Put network code here, with done() in the callback]
}).timeout(500);

#3楼

You might also think about taking a different approach, and replacing the call to the network resource with a stub or mock object. 您可能还会考虑采用其他方法,并用存根或模拟对象替换对网络资源的调用。 Using Sinon , you can decouple the app from the network service, focusing your development efforts. 使用Sinon ,您可以将应用程序与网络服务脱钩,从而集中精力进行开发。


#4楼

从命令行:

mocha -t 100000 test.js

#5楼

(since I ran into this today) (因为我今天遇到了这个)

Be careful when using ES2015 fat arrow syntax: 使用ES2015粗箭头语法时要小心:

This will fail : 这将失败:

it('accesses the network', done => {

  this.timeout(500); // will not work

  // *this* binding refers to parent function scope in fat arrow functions!
  // i.e. the *this* object of the describe function

  done();
});

EDIT: Why it fails: 编辑:为什么失败:

As @atoth mentions in the comments, fat arrow functions do not have their own this binding. 作为@atoth提到的意见, 胖箭头函数没有自己的这种结合。 Therefore, it's not possible for the it function to bind to this of the callback and provide a timeout function. 因此,不可能将it函数绑定到回调并提供超时功能。

Bottom line : Don't use arrow functions for functions that need an increased timeout. 底线 :不要将箭头功能用于需要增加超时的功能。


#6楼

If you wish to use es6 arrow functions you can add a .timeout(ms) to the end of your it definition: 如果希望使用es6箭头功能,则可以在it定义的末尾添加.timeout(ms)

it('should not timeout', (done) => {
    doLongThing().then(() => {
        done();
    });
}).timeout(5000);

At least this works in Typescript. 至少这在Typescript中有效。

你可能感兴趣的:(如何在Mocha中增加单个测试用例的超时)