我想測驗一個A在其中呼叫多個其他函式的函式,這些函式可能會引發錯誤。
這是我的代碼的抽象:
// file A.ts
const A = (args: any[]): boolean => {
(() => {
// nested function which throws
throw new RangeError("some arg not correct")
})()
return true
}
和
// file main.test.ts
test("should throw an error", () => {
expect(A()).toThrow()
})
我如何在 Jest 中適當地測驗這個?
測驗不會成功,jest 會記錄拋出的錯誤。這是一個
uj5u.com熱心網友回復:
我不擅長打字稿,所以我使用常規 JS 撰寫了示例。
事實證明,您不需要呼叫該A函式來測驗它是否拋出:
// throw.test.js
const A = () => {
(() => {
// nested function which throws
throw new RangeError("some arg not correct")
})();
};
test("should throw an error", () => {
expect(A).toThrow();
})
哪個輸出
> jest
PASS ./throw.test.js
? should throw an error (6ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.404s
Ran all test suites.
如果你確實想呼叫這個函式,比如說傳遞一個引數,在另一個傳遞給期望的函式中呼叫它:
// throw2.test.js
const A = () => {
(() => {
// nested function which throws
throw new RangeError("some arg not correct")
})();
};
test("should throw an error", () => {
expect(() => A('my-arg')).toThrow();
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/387164.html
標籤:javascript 打字稿 错误处理 玩笑
上一篇:如何匯入同名路徑不同的組件?
