简体   繁体   English

使用 jest 验证异步函数抛出非错误对象

[英]Verify async function throws non-error object using jest

Using the jest framework, how can I verify that my async function throws something other than an Error ?使用jest框架,我如何验证我的异步函数是否抛出了Error以外的东西?

In my examples below, the first one works as expected, as the function being tested throws an Error .在我下面的示例中,第一个按预期工作,因为正在测试的函数会引发Error The second example, where the function throws a string , doesnt work - jest doesnt verify that the function throws.第二个例子,函数抛出一个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);
});

I don't think you need 'rejects' in either case.我认为在任何一种情况下都不需要“拒绝”。 According to the docs it's not clear if the toThrow method expects results to be derived from Error .根据文档,不清楚toThrow方法是否期望结果来自Error There is a regex form which might validate against a string.有一个正则表达式表单可能会针对字符串进行验证。

rejects says that it unwraps the rejection so it can be matched, and that might give you the error message string from Error , or a string if the result was a string. rejects说它解开拒绝,以便可以匹配,这可能会给你来自Error的错误消息字符串,或者如果结果是字符串,则为字符串。

Dave's point was absolutely right;戴夫的观点是绝对正确的。 using rejects.toThrow was not the right way to go here.使用rejects.toThrow不是正确的方法。

Instead, I'm managed to verify the expected behaviour by simply catching the error and verifying it's value.相反,我设法通过简单地捕获错误并验证它的值来验证预期的行为。


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);
});

Note that expect.assertions(1) is important here.请注意, expect.assertions(1)在这里很重要。 Without this, if the code being tested was updated to not throw, the test would still pass.没有这个,如果被测试的代码被更新为抛出,测试仍然会通过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM