San*_*Rey 11 javascript node.js typescript jestjs
我有一个函数 ( hostelService.book) 返回一个 promise: returnPromise.resolve(response);
并且我做了这个测试:
const action = async () => {
await hostelService.book(id);
};
await expect(action).rejects.toThrow();
Run Code Online (Sandbox Code Playgroud)
但我有这个错误:
Matcher error: received value must be a promise
Run Code Online (Sandbox Code Playgroud)
Soh*_*raf 16
Jest 正在抛出此错误,Matcher error: received value must be a promise因为 expect您只是在传递函数引用。没有 () -action 只是一个函数引用,它不会返回任何东西。
要解决这个问题,你必须像expect一样调用函数,action()这样它就会返回promise对象。
第二部分,你必须抛出错误。Promise.reject(new Error('some error'));在拒绝中,因此tothrow可以完全填充条件。
例子:
function hostelService() {
return Promise.reject(new Error('some error'));
}
const action = async () => {
await hostelService();
};
it( "Should throw the error", async () => {
await expect(action()).rejects.toThrow('some error');
});
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助。
.rejects您的测试失败是因为您正在等待 Promise(因此,当您调用它时,它不再是 Promise )。如果您await从最后一条语句中删除,它应该可以解决问题:
const action = async () => {
await hostelService.book(id);
};
expect(action()).rejects.toThrow();
Run Code Online (Sandbox Code Playgroud)
这是其背后的一些理由。async自动将您的返回类型包装到 Promise 中。但是,当您调用 时await,它会同步“解包”给定 Promise 的值,因此它无法调用.rejects结果(除非您将 Promise 包装到另一个 Promise 中)。
我写了一个小例子来说明我的意思。
看来你几乎已经拥有了。我创建了一个codesandbox,其中包含一个抛出错误的函数和一个通过的测试。npm run test您可以在codesandbox 内的终端中运行它。这是链接:
https://codesandbox.io/s/musing-goodall-ssss4?fontsize=14&hidenavigation=1&theme=dark
但基本上代码是这样的:
const action = async () => {
throw new Error("error!")
}
describe("func", () => {
it("should fail", async () => {
await expect(action()).rejects.toThrow()
})
})
Run Code Online (Sandbox Code Playgroud)
与您显示的代码的区别在于action()缺少调用,也许这是类型错误。我不知道这是一个错误,还是这不仅仅是代码,您只是想解释一下您想要的内容。将来,为了更好地理解并帮助您未来的“帮助者”,您应该发布代码片段(或进行修改以避免财产问题)。
| 归档时间: |
|
| 查看次数: |
15056 次 |
| 最近记录: |