我在测试用例中提交网络请求,但这有时需要超过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
.timeout(ms)
it('should not timeout', (done) => { doLongThing().then(() => { done(); }); }).timeout(5000);
至少这适用于Typescript .
如果您在NodeJS中使用,则可以在package.json中设置超时
"test": "mocha --timeout 10000"
然后你可以使用npm运行:
npm test
从命令行:
mocha -t 100000 test.js
您可能还会考虑采用不同的方法,并使用存根或模拟对象替换对网络资源的调用 . 使用Sinon,您可以将应用程序与网络服务分离,从而集中您的开发工作 .
(因为我今天碰到了这个)
使用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:
正如@atoth在评论中提到的那样,胖箭头函数没有自己的绑定 . 因此,it函数不可能绑定到回调函数并提供超时函数 .
结论:不要对需要增加超时的函数使用箭头函数 .
For test navegation on Express:
const request = require('supertest'); const server = require('../bin/www'); describe('navegation', () => { 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) 它避免使用所有这些时间 .
setTimeout(done, 3500)
done
clearTimeout(timeOut)
7 回答
你去:http://mochajs.org/#test-level
对于箭头功能使用如下:
如果您想使用es6箭头功能,可以在
it
定义的末尾添加.timeout(ms)
:至少这适用于Typescript .
如果您在NodeJS中使用,则可以在package.json中设置超时
然后你可以使用npm运行:
从命令行:
您可能还会考虑采用不同的方法,并使用存根或模拟对象替换对网络资源的调用 . 使用Sinon,您可以将应用程序与网络服务分离,从而集中您的开发工作 .
(因为我今天碰到了这个)
使用ES2015胖箭头语法时要小心:
This will fail :
EDIT: Why it fails:
正如@atoth在评论中提到的那样,胖箭头函数没有自己的绑定 . 因此,it函数不可能绑定到回调函数并提供超时函数 .
结论:不要对需要增加超时的函数使用箭头函数 .
For test navegation on Express:
在该示例中,测试时间为4000(4s) .
注意:
setTimeout(done, 3500)
是次要的,因为done
在测试时被调用,但clearTimeout(timeOut)
它避免使用所有这些时间 .