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);
});
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
});
Note that toThrow was fixed for promises in PR 4884 and only works in 21.3.0+.
So this will only work if you are using Jest version 22.0.0 or higher.
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
});
...and optionally check the Error thrown by checking spy.mock.calls[0][0].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With