This Week I Learned: Expecting Node Asynchronous Errors [2022–04–01]

Photo by Gabriel Heinzer on Unsplash

This is not an April Fool, you really should expect them!

I was writing some code in Node and testing in Jest, but I had trouble writing expect() assertions in a way that caught errors thrown from asynchronous code.

Synchronous? No problem. expect(something()).toThrow();

Async and no throw? No problem. expect(something()).toResolve.toEqual(expectedResult);

Async and expecting an error? No way. expect(something()).toResolve.toThrow() absolutely did not work for me. It didn’t stop on the error being thrown and I got a stack trace printed asynchronously in logs.

I really wanted to write test assertions that read fluently.

So, I wrote my own helper.

Usage:

expect(await asyncErrorFrom(asyncFunction)).toEqual(Error(message));

Code:

async function asyncErrorFrom(asyncFunction) {
let caught = null;
try {
await asyncFunction();
} catch (error) {
caught = error;
}
return caught;
}

--

--

Peter Brownlow

Software builder, people manager, topical deep-dive enthusiast