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 aPromise
that should reject with anError
so the syntax should be: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 aspy
tocatch
:...and optionally check the
Error
thrown by checkingspy.mock.calls[0][0]
.