[英]How to use async-await and then in one Mocha test with done?
因此,我进行了如下测试:
it 'sample test', (done)->
await Promise.resolve 0
Promise.resolve 0
.then ->
done()
null
注意,最后的null
是为了避免返回Promise。 但是,测试属于经典的"Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both"
我检查了结果JS代码,没什么奇怪的:
it('Sample test', async function(done) {
await Promise.resolve(0);
Promise.resolve(0).then(function() {
return done();
});
return null;
});
我不明白这是怎么回事,因为(按照我的想法)此代码不应返回promise。 另外,当我将第一个承诺(带有await
)包装到setTimeout
,它可以正常工作。
it 'working test', (done)->
setTimeout ->
await Promise.resolve 0
, 0
Promise.resolve 0
.then ->
done()
null
当然,使用setImmediate
代替setTimeout
也可以,所以我认为这种情况下的解决方法是回调。 但这是极其肮脏的解决方案。 then
如何在一个测试中更清晰地混合, async-await
和done
?
在函数体中使用await
将测试函数转换为async
函数。
async
函数总是返回Promise
。
因此,在这种情况下:
it('Sample test', async function(done) {
await Promise.resolve(0);
Promise.resolve(0).then(function() {
return done();
});
return null;
});
...测试函数返回的Promise
将解析为null
。
在您的另一个示例中,Mocha不会抱怨,因为代码编译为此:
it('working test', function(done) {
setTimeout(async function() {
return (await Promise.resolve(0));
}, 0);
Promise.resolve(0).then(function() {
return done();
});
return null;
});
...因为现在await
在传递给setTimeout
的函数体内。
(请注意,这两个测试的行为非常不同 )。
没有理由同时使用done
和async / await
测试函数(或返回Promise
函数),因此Mocha失败并显示该错误。
您的第一个测试可以简化为:
it 'sample test', ()->
await Promise.resolve 0
await Promise.resolve 0
...或者如果您需要在第二个Promise
进行工作, then
执行以下操作:
it 'sample test', ()->
await Promise.resolve 0
await Promise.resolve 0
.then ->
// do stuff here
在Mocha v3.0.0及更高版本中,返回Promise并调用done()
将导致异常,因为通常这是一个错误-docs
由于async function
总是返回 Promise
,因此会出现此错误。 可能的解决方案:
删除async function
it('Sample test', function(done) { Promise.resolve(0) .then(function() { ... }) .then(function() { ... // if necessary }) .then(function() { done(); }); });
退货Promise
it('Sample test', function() { return Promise.resolve(0) .then(function() { ... }) .then(function() { ... // if necessary }); });
使用async/await
it('Sample test', async function() { await Promise.resolve(0); await Promise.resolve(0); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.