我想在一個地方捕獲所有例外,但目前我不能這樣做:
如果你喜歡更多的 try/catch,有一件重要的事情要注意。以下代碼不會捕獲錯誤:
[...]
記住:被拒絕的 Promise 將在堆疊中向上傳播,除非您捕獲它。要在 try/catch 中正確捕獲錯誤,您可以像這樣重構:whatever().catch(err => console.error(err));
但這是我想要的代碼:
async function getMtgJsonVersion() {
try {
const response = await axios(metaUrl).catch((err) => { throw err; });
const { data: { meta: { version } } } = response;
return version;
} catch (error) {
console.error(`Could not fetch MTG JSON metadata: ${error}`);
throw error;
}
}
和我的測驗:
// console.error is mocked higher up in the test file
it.only('handles errors in fetching', async () => {
expect.assertions(2);
axios.mockReset(); // I use mockImplementationOnce elsewhere
axios.mockRejectedValueOnce(new Error('bang'));
expect(() => getMtgJsonVersion()).rejects.toThrow('bang');
expect(console.error).toHaveBeenCalledWith(expect.stringContaining('bang'));
});
但是當我運行它時,我發現最后的期望沒有得到滿足?
expect(jest.fn()).toHaveBeenCalledWith(...expected) Expected: StringContaining "bang" Number of calls: 0
我希望能在一個地方接住我所有的投球,但看起來并不像我想象的那么簡單。
這是可能的,如何?
uj5u.com熱心網友回復:
因為expect(fn).rejects.*是異步操作,所以需要“一點時間”才能完成。
在您的代碼中,expect(console.error).toHaveBeenCalledWith(expect.stringContaining('bang'))將expect(() => getMtgJsonVersion()).rejects.toThrow('bang');在行之前運行。那時,console.log還沒有被呼叫。
為了讓它按你的預期作業,你必須等到 getMtgJsonVersion完成,然后在日志函式上斷言。rejects.toThrow('bang')回傳一個承諾,然后用await關鍵字等待它:
await expect(() => getMtgJsonVersion()).rejects.toThrow('bang');
expect(console.error).toHaveBeenCalledWith(expect.stringContaining('bang'));
我的注意:避免try/catch在“子”單元中使用,只需在“最終父”函式中使用它,如果您只想在http請求失敗時進行記錄:
async function getMtgJsonVersion() {
const { data } = await axios(metaUrl).catch((error) => {
console.error(`Could not fetch MTG JSON metadata: ${error}`);
throw error;
});
return data.meta.version.
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/388229.html
標籤:javascript 节点.js 测试 异步等待 玩笑
上一篇:如何正確地從函式回傳
