Skip to main content

Handling errors from async methods in Jest

This blog post might be outdated!
This blog post was published more than one year ago and might be outdated!
· 2 min read
Stephan Hochdörfer
Head of IT Business Operations

While testing an async method with ts-jest I came across a problem. The method throws an error on invalid input.

I created a simple test case like this:

expect(async () => {
await service.createDefaultIssuesForProject('My sample project');
}).toThrow('GitLab ID missing!');

When executing the test, jest died with the following error:

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block,
or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason
"Error: GitLab ID missing!".] { code: 'ERR_UNHANDLED_REJECTION'

I was digging through a ton of blog posts and followed their advice but none really worked. Luckily my co-worker Daniel Ruf knew the answer. Well, actually two to be precise :)

Since the Promise was rejected, I have to tell expect() that:

await expect(
service.createDefaultIssuesForProject('My sample project')
).rejects.toThrow('GitLab ID missing!');

The more complex alternative would be to catch the error myself, and compare the error message with the one that I expect (pun intended):

let errorObj : unknown;
try {
await service.createDefaultIssuesForProject('My sample project');
} catch (error : unknown) {
const e = error as ErrorEvent;
errorObj = e.message;
}
expect(errorObj).toBe('GitLab ID missing!');

I decided to go with the first approach as it felt cleaner to me.