[英]How to increase timeout for a single test case in mocha
我在测试用例中提交网络请求,但这有时需要超过 2 秒(默认超时)。
如何增加单个测试用例的超时时间?
给你: 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);
如果你想使用 es6 箭头函数,你可以在it
定义的末尾添加一个.timeout(ms)
:
it('should not timeout', (done) => {
doLongThing().then(() => {
done();
});
}).timeout(5000);
至少这适用于打字稿。
(因为我今天遇到了这个)
使用 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 在评论中提到的,胖箭头函数没有自己的this绑定。 因此,它不可能为它的功能绑定到这个回调并提供超时功能。
底线:不要对需要增加超时的函数使用箭头函数。
如果您在 NodeJS 中使用,那么您可以在 package.json 中设置超时
"test": "mocha --timeout 10000"
然后你可以使用 npm 运行,如:
npm test
从命令行:
mocha -t 100000 test.js
您可能还考虑采用不同的方法,用存根或模拟对象替换对网络资源的调用。 使用Sinon ,您可以将应用程序与网络服务分离,从而专注于您的开发工作。
对于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)
它避免了所有这些时间的使用。
这对我有用! 找不到任何东西使它与 before() 一起工作
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.