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

我在一个测试用例中提交了一个网络请求,但这有时需要超过2秒(默认超时)。

如何增加单个测试用例的超时时间?

181590 次浏览

在这里:http://mochajs.org/#test-level

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

对于箭头函数,使用方法如下:

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

您还可以考虑采用不同的方法,用存根或模拟对象替换对网络资源的调用。使用西农,你可以将应用从网络服务中解耦,集中你的开发精力。

从命令行:

mocha -t 100000 test.js

(因为我今天碰到了这个)

使用ES2015胖箭头语法时要小心:

这将失败:

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

编辑:为什么它失败了:

正如@atoth在评论中提到的,脂肪箭头函数没有自己的绑定。因此,函数不可能绑定回调的并提供超时函数。

底线:对于需要增加超时时间的函数,不要使用箭头函数。

如果你想使用es6箭头函数,你可以在你的it定义的末尾添加一个.timeout(ms):

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

至少在Typescript中是这样的。

如果你在NodeJS中使用,那么你可以在package.json中设置timeout

"test": "mocha --timeout 10000"

然后你可以像这样使用NPM运行:

npm test

对于Express上的测试导航:

const request = require('supertest');
const server = require('../bin/www');


describe('navigation', () => {
it('login page', function(done) {
this.timeout(4000);
const timeOut = setTimeout(done, 3500);


request(server)
.get('/login')
.expect(200)
.then(res => {
res.text.should.include('Login');
clearTimeout(timeOut);
done();
})
.catch(err => {
console.log(this.test.fullTitle(), err);
clearTimeout(timeOut);
done(err);
});
});
});

本例中测试时间为4000 (4s)。

注意:setTimeout(done, 3500)对于在测试时间内调用done是次要的,但clearTimeout(timeOut)避免在所有这些时间内使用。

这对我很管用!找不到任何东西让它工作之前()

describe("When in a long running test", () => {
it("Should not time out with 2000ms", async () => {
let service = new SomeService();
let result = await service.callToLongRunningProcess();
expect(result).to.be.true;
}).timeout(10000); // Custom Timeout
});