![](/img/trans.png)
[英]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.