How do you concisely test if a void async function executed successfully with jest? I'm using TypeScript.
// foo.ts
export class Foo {
public async bar(): Promise<void> {
await someAsync();
}
}
How to test that new Foo().bar()
does not throw an error?
There is an alternate form of test that fixes this. Instead of putting the test in a function with an empty argument, use a single argument called done . Jest will wait until the done callback is called before finishing the test.
Testing With Async / Await As we saw in the previous section, Jest will know that we are dealing with asynchronous code if we return a Promise object form the test function. If we declare the test function as async , it will implicitly make the function to return a Promise.
Try-catch with async/await (bad) It looks like using try-catch with async/await is the easiest way to achieve this as the rejected value is thrown: it("rejects (bad)", async () => { try { await promiseMe("Error"); } catch (e) { expect(e). toEqual("Error"); } }); But wait.
In order to mock asynchronous code in Jest, more specifically Promises, you can use the mockResolvedValue function. This will mock the return value of the Promise to be 42. In order to test a Promise in Jest, you need to turn your it block into async in order to use the await keyword in front of an expect statement.
This is the most semantic way I've found. It is even just a translation of the test name.
describe("Foo.bar()", () => {
test("Should not throw", async () => {
await expect(new Foo().bar()).resolves.not.toThrow();
});
});
The Promise has the advantage that it should not throw at all, rather be resolved or rejected. On the other hand the toBe()
assertion expects an argument, even though there is a Promise<void>
in TypeScript.
So what if there is no argument passed (or the argument is void) but it is still evaluated. The the argument is undefined
.
test("Should resolve", async () => {
await expect(new Foo().bar()).resolves.toBe(undefined);
});
Testing for not.toThrow()
happend to be a false friend for me, because my Foo.bar()
did not throw, nor was it resolved either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With