我编写了一个函数,它接受一些参数,并且在函数内部使用一个类,该类具有来自第三方库的函数,该函数返回一个承诺,并且我在自己的函数中返回该承诺的结果。喜欢:
return client.track(data) // client.track is from a 3rd party lib that should return a promise
现在我想在我的 mocha + chai 测试文件中测试承诺的返回。我用输入导入这个函数,我应该得到结果。像这样的东西:
const result = await myfunc(x,y) // Should return the result of a promise
现在我想测试在 mocha + chai 中承诺是否真正得到解决或拒绝,就像使用
chai.expect(...)
我该怎么做?
查看 npm 包
chai-as-promised
(https://www.npmjs.com/package/chai-as-promised)。它是 chai 库的扩展,提供对 Promise 的支持。
您可以通过以下方式进行设置
const chai = require("chai")
const chaiAsPromised = require("chai-as-promised")
chai.use(chaiAsPromised)
chai.should()
promiseFunction(args).should.be.rejectedWith(SomeError)
promiseFunction().should.eventually.be.a('array')
查看文档以更好地了解此插件的强大功能:)
这可行,但需要一点样板。
await expect(await myPromise.then(() => true)).to.be.true
这是我使用
mocha
来测试被拒绝的承诺。它丑陋且冗长,但避免添加更多测试依赖项,并避免误报。
describe('when an awaited promise is rejected', () => {
it('should raise an error', async () => {
try {
await someAsyncFunctionThatWillReject()
assert(false) // will fail the test if no error
} catch(e) {
assert(true) // passes only if there was an error
}
})
})
最后的
assert(true)
并不会真正影响测试结果,但它使测试更具可读性。
也许你需要在 catch 部分中有一个特定的断言,例如:
chai.expect(e).to.be.an.instanceOf(Error);
chai.expect(e.message).to.be.not.null;
expect 方法来自 chai 库,该库通常与 mocha 合作。