Testing API calls in React

Boluwatife Fakorede
Nerd For Tech
Published in
2 min readMar 29, 2021

--

You can get part one of this article here. It focuses on Mocking APIs for frontend developers.

In the words of Kent C. Dodds.

The more your tests resemble the way your software is used, the more confidence they can give you. — Kent C. Dodds.

While writing tests, it is best to focus on the use cases of our applications. This way, our tests mimic our users, and we are not focused on the implementation details.

Since we are testing for our application use cases, it is important to test for the interaction with data (Hence API requests).

Previously, to test API requests, we would probably have to mock “ window. fetch” or “Axios,” but our users won’t do that, would they? Hence there should be a better approach.

Mocking API requests with msw

Considering the various limitations of mocking out fetch or Axios, it is bliss with a tool like msw, allowing the same mock definition for testing, development, and debugging.

msw intercepts the request on the network level; hence our application or test knows nothing about the mocking.

In the previous article, I demonstrated how to use msw to mock APIs. The good news is, we can use the same mocks for our tests!

Refactoring mock APIs

Let’s get started by refactoring our setup workers since we want to share our mock APIs (API handlers).

Now the handlers are alone in a new file, and we can share them between our dev-server and test-server. Let’s update the dev-server.

Our dev-server is a lot shorter now, and everything still works, but we are not ready yet to writing tests; we need to set up a test server. Let’s do that.

Setup test server

If you notice, the test-server is different from the dev-server as the “setupServer” is gotten from “msw/node.”

It is good to note that you have to install “whatwg-fetch” as Node.js does not support fetch if you are using the fetch API. For our use case, we bootstrap our application with create-react-app, which handles this automatically.

We would establish API mocking on the global level by modifying the setupTests.ts file (provided by create-react-app) as shown below.

NB: You can establish a global level for API mocking if you are not using create-react-app by following the docs.

Testing React API calls.

Let’s test our todos rendering and adding a new todo.

In the above test, we don’t have to mock out “fetch” or “Axios.” We are testing exactly how our users will use the application, a real API request is made, and we get the mock response which is great and gives us much more confidence.

Thank you for reading.

--

--

Boluwatife Fakorede
Nerd For Tech

A frontend developer, while at that, just a curious cat that loves to share what he knows.