问题描述
我看过这个问题,期望得到一个Promise
上班.在我的情况下,Error
抛出在Promise
之前和之外.
I have seen this question which expects a Promise
to work. In my case the Error
is thrown before and outside a Promise
.
在这种情况下如何断言错误?我已经尝试过以下选项.
How can I assert the error in this case? I have tried the options below.
test('Method should throw Error', async () => {
let throwThis = async () => {
throw new Error();
};
await expect(throwThis).toThrow(Error);
await expect(throwThis).rejects.toThrow(Error);
});
推荐答案
调用throwThis
会返回Promise
,应以Error
拒绝,因此语法应为:
Calling throwThis
returns a Promise
that should reject with an Error
so the syntax should be:
test('Method should throw Error', async () => {
let throwThis = async () => {
throw new Error();
};
await expect(throwThis()).rejects.toThrow(Error); // SUCCESS
});
请注意,toThrow
在 PR 4884 和仅适用于21.3.0+ .
因此,这仅在您使用Jest
22.0.0或更高版本时有效.
So this will only work if you are using Jest
version 22.0.0 or higher.
如果使用的是早期版本的Jest
,则可以将spy
传递给catch
:
If you are using an earlier version of Jest
you can pass a spy
to catch
:
test('Method should throw Error', async () => {
let throwThis = async () => {
throw new Error();
};
const spy = jest.fn();
await throwThis().catch(spy);
expect(spy).toHaveBeenCalled(); // SUCCESS
});
...并通过检查Error抛出的 > .
...and optionally check the Error
thrown by checking spy.mock.calls[0][0]
.
这篇关于如何使用带有Jest的toThrow断言引发Error的异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!