[英]Expect a function throw for synchronous code inside asynchronous function using Jest with Create React App (CRA)
我正在使用Jest與Create React App進行測試,並且試圖與同步代碼一起測試異步函數,並且當同步部分出現錯誤時,我需要將其拋出。
測試包括在接收錯誤的參數類型時期望函數拋出。
該函數拋出“無效參數”。 當接收除“ undefined” (不帶參數的函數)或“ number”以外的參數類型時。
USER_API是要調用的API URL。
這是函數:
export const getUsers = async (count, ...rest) => {
if (["undefined", "number"].includes(typeof count) && rest.length === 0) {
const response = await fetch(USERS_API);
const users = await response.json();
if (count && typeof count === "number") {
return users.slice(0, count - 1);
}
return users;
}
throw "Invalid arguments.";
};
這是測試:
it.only("should throw on invalid arguments", () => {
const str = "hello";
expect(() => getUsers(str)).toThrow(/invalid/gi);
});
我擴展了函數拋出
但是運行測試顯示:預期該函數將引發與錯誤匹配的錯誤:/ invalid / gi但是它沒有引發任何異常。
測試方法正確還是我寫的測試不好? 如果不好,我該如何改善?
謝謝。
由於您的getUsers
是一個異步函數,因此它返回Promise
。 因此,為了對其進行測試,您需要執行以下操作:
it.only ( "should throw on invalid arguments", () => {
const str = "hello";
getUsers ( str ).then ( function ( success ) {
}, function ( err ) {
expect ( err ).toBe ( /invalid/gi );
} );
測試異步代碼的其他方法之一是:
it.only ( "should throw on invalid arguments", () => {
const str = "hello";
try {
await getUsers("hello");
} catch (e) {
expect(e).toMatch(/invalid/gi);
}
});
您可以在此處獲得更多詳細信息: 笑話:測試異步代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.