[英]Warning: a promise was rejected with a non-error: [object GeolocationPositionError]
[英]Verify async function throws non-error object using jest
使用jest
框架,我如何驗證我的異步函數是否拋出了Error
以外的東西?
在我下面的示例中,第一個按預期工作,因為正在測試的函數會引發Error
。 第二個例子,函數拋出一個string
,不起作用 - 開玩笑不驗證函數拋出。
// Works as expected
test('verify error thrown', async () => {
const expected = new Error('actual-error');
const fn = async () => { throw expected; };
await expect(fn()).rejects.toThrow(expected);
});
// Fails with: Received function did not throw
test('verify non-error thrown', async () => {
const expected = 'non-error';
const fn = async () => { throw expected; };
await expect(fn()).rejects.toThrow(expected);
});
戴夫的觀點是絕對正確的。 使用rejects.toThrow
不是正確的方法。
相反,我設法通過簡單地捕獲錯誤並驗證它的值來驗證預期的行為。
test('verify non-error thrown', async () => {
const expected = 'non-error';
const fn = async () => { throw expected; };
await fn().catch(error => expect(error).toStrictEqual(expected));
expect.assertions(1);
});
請注意, expect.assertions(1)
在這里很重要。 沒有這個,如果被測試的代碼被更新為不拋出,測試仍然會通過。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.