这段代码:
it('should not say overspecified', async function (done) {
await new Promise(resolve => resolve());
done();
});
Run Code Online (Sandbox Code Playgroud)
导致这样的情况:Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.
但是......我不会回报承诺。我只是在等待一个承诺。
如果我将代码更改为这样,它就会起作用:
it('should not say overspecified',function(){
return new Promise(async resolve=>{
await (new Promise(resolve=>resolve()));
resolve();
})
});
Run Code Online (Sandbox Code Playgroud)
为什么它只在我不必要地将代码包装在 Promise 中时才起作用?
这段代码:
it('should not say overspecified', async function (done) {
await new Promise(resolve => resolve());
done();
});
Run Code Online (Sandbox Code Playgroud)
原因如下:错误:解析方法指定过多。指定回调或者返回Promise;不是都。
因为按照设计async functions总是返回 a 。Promise
在 Mocha 中,您可以返回 aPromise 或使用done,但不能同时返回两者。
我会这样做:
// Do not pass `done` as a parameter to `it` callback.
it('should not say over specified', function() {
return new Promise(resolve => resolve())
});
Run Code Online (Sandbox Code Playgroud)
或者如果你想使用await:
// Do not pass `done` as a parameter to `it` callback.
it('should not say overspecified', async function () {
await new Promise(resolve => resolve());
});
Run Code Online (Sandbox Code Playgroud)
这是一个实际的async/await例子:
require('chai').should()
const getFoo = async () => 'foo'
describe('#getFoo()', () => {
it('returns foo', async () => {
const foo = await getFoo()
foo.should.equal('foo')
})
})
Run Code Online (Sandbox Code Playgroud)
您应该done仅用于基于回调或基于事件的代码。
完全没有必要将它与Promise基于 - 的代码(例如常规 Promises 或async/await.
如果我可以控制我正在测试的代码(我编写的),我会“承诺”我从外部回调样式 API 使用的所有基于回调的代码,因此我正在使用的代码的整个异步 API 始终使用承诺。如果合理使用,那么它显然也会使测试变得更容易(通过完全消除完成的需要)。
| 归档时间: |
|
| 查看次数: |
3471 次 |
| 最近记录: |