繁体   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