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

本文介绍了如何在Mocha测试框架中针对单个测试用例增加超时时间,特别是在测试中遇到网络请求导致超时的情况。推荐使用`this.timeout()`方法来调整超时设置,并提醒避免使用ES2015箭头函数,因为它们无法正确绑定`this`上下文。此外,还提出了使用Sinon进行存根或模拟对象替代网络请求以简化测试的建议。
摘要由CSDN通过智能技术生成

本文翻译自: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中有效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值