Jest/React – mocking async functions

Let’s say you have a component that calls to an API in a useEffect. This API data will be used to update some component state.

When writing a component test you will want to mock this API call and provide a stub for it.

Many times I have seen code that looks like this:

What we should really be doing is this:

Why is the second one better? In the first example we are mocking an asynchronous function with a synchronous one, this is a bad thing because we are now stepping a little further away from the real world in our test, when our component runs for real the call will be asynchronous and we need to know it can handle that. In the second example we are telling jest that this is an asynchronous function, and it should treat it as such, and once it is resolved we get our mock.

Here is an example of code for when you might want to add a synthetic delay to your mocked function and really test how robust it is:

We are back to stubbing the entire implementation of the API call, but we are providing a promise with a synthetic delay for that implementation, so we are still mirroring real world.