Testing exceptions in async functions with jest
Sync world #
Write test that check a function throws can be daunting. This is a first attempt:
try {
functionThatThrows();
} catch (error) {
expect(error).toEqual(...)
}
The above code have several problems. The most important is that if the function doesn't throw, the test passes. Bad.
Fortunately, jest has you covered:
expect(functionThatThrows).toThrow(...)
Async world #
But what happens if the "functionThatThrows" is async (returns a promise)?
This doesn't work:
// DO NOT try this at home:
expect(await functionThatThrows()).toThrow(...)
But there are other alternatives explained here. My favourite is:
await expect(asyncFunction()).rejects.toThrow(...)
A real world example:
await expect(UserFactory.create({ name: null })).rejects.toThrow(
/NULL into column 'name'/
);
Happy testing 🖖