我在mocha测试套件中使用setTimeout来插入一个20秒的延迟,然后在describe块中进行it()的最后一次调用 . 虽然,我正在使用done(),但我仍然在终端上得到以下错误:
错误:超过2000毫秒的超时 . 对于异步测试和挂钩,确保调用“done()”;如果返回一个promise,请确保它解决错误:超过2000ms的超时 . 对于异步测试和挂钩,确保调用“done()”;如果返回一个承诺,确保它解决
我究竟做错了什么?
以下是我的代码:
describe('Testing get and post APIs', ()=> {
it('Series of get and post', (done) => {
chai.request(server)
.post('/thisis/1st_post')
.send()
.end((err, res) => {
expect(res.statusCode).to.equal(200);
chai.request(server)
.get('/thisis/1st_get')
.send()
.end((err, res) => {
expect(res.statusCode).to.equal(200);
setTimeout(function() {
chai.request(server)
.post('/thisis/last_post')
.send()
.end((err, res) => {
expect(res.statusCode).to.equal(200);
done();
})
},20000);
});
});
});
});
谢谢 .
2 回答
如果您希望测试运行器等待的时间超过默认时间,则需要更改超时值 . 例如,尝试在
describe
块的开头添加它:this.timeout(30 * 1000); // wait up to 30 seconds before failing from timeout
另见:Change default timeout for mocha&https://mochajs.org/api/test#timeout
但是,根据您所需的20秒延迟的原因,延长测试超时可能是错误的解决方案 . 如果您正在使用延迟来处理请求承诺永远不会解决的情况,那么更好的方法是使用Promise.race . 如果不了解你的情况,我很难判断 .
超时设置为
20000 (20 seconds)
,但基于错误的测试超时为2000 (2 seconds)
. 这意味着我们需要为测试本身设置更大的超时 .我想知道我们是否可以像下面那样进行测试 . 它更清洁,更易于维护 .
希望能帮助到你 .