【发布时间】:2013-04-04 23:16:00
【问题描述】:
我在测试用例中提交网络请求,但这有时需要超过 2 秒(默认超时)。
如何增加单个测试用例的超时时间?
【问题讨论】:
标签: javascript mocha.js
我在测试用例中提交网络请求,但这有时需要超过 2 秒(默认超时)。
如何增加单个测试用例的超时时间?
【问题讨论】:
标签: javascript mocha.js
给你: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);
【讨论】:
.timeout(500) 添加到it(...).timeout(500) 的末尾
您也可以考虑采用不同的方法,用存根或模拟对象替换对网络资源的调用。使用Sinon,您可以将应用与网络服务分离,专注于您的开发工作。
【讨论】:
从命令行:
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 在 cmets 中提到的,胖箭头 函数没有自己的 this 绑定。因此,it 函数不可能绑定到回调的 this 并提供 timeout 函数。
底线:不要将箭头函数用于需要增加超时的函数。
【讨论】:
this 绑定——不同的方式表明它们有某种,只是不同。它们只有词法范围。你不能绑定不存在的这个。这就是为什么.bind、.call 等无法使用它的原因。
this 是什么了。
如果您想使用 es6 箭头函数,您可以在 it 定义的末尾添加 .timeout(ms):
it('should not timeout', (done) => {
doLongThing().then(() => {
done();
});
}).timeout(5000);
至少这在 Typescript 中有效。
【讨论】:
.timeout 不包含在 mocha 的肯定类型分型中:i.imgur.com/jQbWCn1.png - 使用 this.timeout(2000) 或 this.slow(500) 与常规旧函数一起工作并且编译没有错误
it,不适用于describe。
describe() 或context() 执行此操作?
.timeout 现在包含在 distinctlyTyped 的 Mocha 类型中:Mocha.IRunnable。但是,如果您使用 Webstorm IDE 运行这些测试,请注意:无论出于何种原因,WebStorm 的 Mocha 集成插件仍然无法识别附加了 .timeout() 的 Mocha 测试(这意味着旁边没有出现“运行”按钮它们),因此我主张避免使用箭头函数以允许使用this.timeout()。
如果你在 NodeJS 中使用,那么你可以在 package.json 中设置超时
"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) 它一直避免使用。
【讨论】:
这对我有用!找不到任何东西可以使它与 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
});
【讨论】: