Testing asynchronous code

The rest of the methods provided by our service are asynchronous and use the Fetch API. To test those methods, we need to discover how to test asynchronous code with Jest and how to use mocks (for example, to avoid side effects when the Fetch API is called).

First of all, the good news is that Jest fully supports testing asynchronous code in general, whether that code works with callbacks, Promises, or async/await. You can find the related official documentation here: https://jestjs.io/docs/en/asynchronous. Since we're using async and await, we'll focus on them.

We can simply create an asynchronous test case by adding the async keyword in front of the test function definition:

it('should fail if the response does ...

Get Learn TypeScript 3 by Building Web Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.