簡體   English   中英

使用 jest 驗證異步函數拋出非錯誤對象

[英]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);
});

我認為在任何一種情況下都不需要“拒絕”。 根據文檔,不清楚toThrow方法是否期望結果來自Error 有一個正則表達式表單可能會針對字符串進行驗證。

rejects說它解開拒絕,以便可以匹配,這可能會給你來自Error的錯誤消息字符串,或者如果結果是字符串,則為字符串。

戴夫的觀點是絕對正確的。 使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM