gpt4 book ai didi

mocha.js - 测试混合的基于异步/Promise 的代码和基于回调的代码

转载 作者:行者123 更新时间:2023-12-05 03:04:25 24 4
gpt4 key购买 nike

这段代码:

it('should not say overspecified', async function (done) {
await new Promise(resolve => resolve());
done();
});

原因:错误:解析方法指定过多。指定一个回调*或*返回一个Promise;不是两者。

但是...我不会返回 Promise。我只是在等待一个 promise 。

如果我将我的代码改成这样,它就可以工作了:

it('should not say overspecified',function(){
return new Promise(async resolve=>{
await (new Promise(resolve=>resolve()));
resolve();
})
});

为什么只有当我将我的代码不必要地包装在 Promise 中时它才有效?

最佳答案

This code:

it('should not say overspecified', async function (done) {
await new Promise(resolve => resolve());
done();
});

Causes this: Error: Resolution method is overspecified. Specify a callback or return a Promise; not both.

因为异步函数总是return a Promise , 通过设计。

在 Mocha 中,您可以返回 Promise 使用done,但是 not both .

我会这样做:

// Do not pass `done` as a parameter to `it` callback.
it('should not say over specified', function() {
return new Promise(resolve => resolve())
});

或者如果你想使用await:

// Do not pass `done` as a parameter to `it` callback.
it('should not say overspecified', async function () {
await new Promise(resolve => resolve());
});

这是一个实用的 async/await 示例:

require('chai').should()

const getFoo = async () => 'foo'

describe('#getFoo()', () => {
it('returns foo', async () => {
const foo = await getFoo()
foo.should.equal('foo')
})
})

您应该只对基于回调或基于事件的代码使用done

完全没有必要将它与基于 Promise 的代码一起使用,例如常规 Promise 或 async/await

测试基于 Promise 和回调的混合代码:

如果我能控制我正在测试的代码(我写的),我“promisify”我从外部回调式 API 使用的所有基于回调的代码,所以代码的整个异步 API我与 always 一起工作时使用 Promises。如果合理使用,那么它显然也会使测试更容易(通过完全消除 done 的需要)。

关于mocha.js - 测试混合的基于异步/Promise 的代码和基于回调的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53029325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com