[英]Jest - how to expect for a thrown error on an async function, which gets caught
我嘗試這樣做:
it('should throw an error', async ()=> {
expect.assertions(1);
try {
await processor({}, MODULE_CONFIG)
}
catch (e) {
expect(e).toBe("[TypeError: Cannot read properties of undefined (reading 'match')]")
}
});
但它給了我這個錯誤:
我在文檔中嘗試toMatch
,但它也給出了一個錯誤(一個看起來更糟的錯誤)
我嘗試改用rejects.tobe
,但我得到了同樣的錯誤:
您的問題在於您要斷言的內容
我假設您從processor
拋出錯誤
如果您是,並且您正在斷言該錯誤是什么,請記住typeof e === object
,而不是string
例如:
function iThrownAnError() {
throw new Error("ups");
}
describe("test a function that throws an error", () => {
it("catches an error as expected", () => {
try {
iThrownAnError();
} catch (e) {
console.log(typeof e); // logs object
console.log(typeof "ups"); // logs string
// the test pass
expect(e).toStrictEqual(new Error("ups"));
// the test would fail
// Expected: "ups"
// Received: [Error: ups]
expect(e).toStrictEqual("ups");
}
});
});
我發現的最佳答案似乎是從錯誤中獲取message
屬性(本質上只是作為字符串的錯誤),然后進行比較。
expect(e.message).toBe("Cannot read properties of undefined (reading 'match')")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.