我想用Mocha
测试异步代码。
我遵循了本教程testing-promises-with-mocha。最后,它说最好的方法是异步/等待。
以下是我的代码,我打算将setTimeout设置为比Mocha默认设置更长。
describe('features', () => {
it('assertion success', async() => {
const resolvingPromise = new Promise( resolve => {
setTimeout(() => {
resolve('promise resolved')
}, 3000)
})
const result = await resolvingPromise
expect(result).to.equal('promise resolved')
})
})
摩卡给我以下错误:
Error: Timeout of 2000ms exceeded. For async tests and hooks,
ensure "done()" is called; if returning a Promise, ensure it resolves...
如何解决该错误?简单设置mocha --timeout 10000
更长?
感谢您的时间!
Mocha: 5.2.0
Chai: 4.2.0
答案 0 :(得分:0)
对于异步测试,您应该调用done()
回调。
describe('features', () => {
it('assertion success', async(done) => { // pass done here
const resolvingPromise = new Promise( resolve => {
setTimeout(() => {
resolve('promise resolved')
}, 3000)
})
const result = await resolvingPromise
expect(result).to.equal('promise resolved')
done() // invoke at end
})
})
答案 1 :(得分:-1)
Mocha具有超时控件。 Mocha docs
语法是:
it('should take less than 500ms', function(done) {
this.timeout(5000); // 5 seconds
setTimeout(done, 3000);
});
您的示例:
describe('features', () => {
it('assertion success', async (done) => {
this.timeout(5000);
const resolvingPromise = new Promise(resolve => {
setTimeout(() => resolve('promise resolved'), 3000)
});
const result = await resolvingPromise();
expect(result).to.equal('promise resolved');
done();
});
});