Expect a function to throw an exception in Jest
Your test fails because you're awaiting the promise (and therefore, it is no longer a Promise when you call .rejects
on it). If you remove await
from the last statement, it should do the trick:
const action = async () => {
await hostelService.book(id);
};
expect(action()).rejects.toThrow();
Here is some rationale behind it. async
automatically wraps your return type into a Promise. However, when you call await
, it synchronously "unwraps" the value of a given Promise and therefore it can't call .rejects
on the result (unless you wrap a Promise into another Promise).
I've composed a small example to illustrate what I mean.
Jest is throwing this error Matcher error: received value must be a promise
because in expect
you are just passing the function reference. Without ()
- action
is just a function reference it will not return anything.
To fix this issue you have to call the function in expect like action()
so it will return the promise object.
And the second part, you have to throw error like. Promise.reject(new Error('some error'));
in the reject so the tothrow
condition can be full filled.
Example:
function hostelService() {
return Promise.reject(new Error('some error'));
}
const action = async () => {
await hostelService();
};
it( "Should throw the error", async () => {
await expect(action()).rejects.toThrow('some error');
});
Hope this will be helpful.