How to write effective tests for React apps with react testing library?

How to write effective tests for React apps with react testing library?

How to write effective tests for React apps with react testing library?

This tutorial demonstrates how to write effective tests for your React application with react testing library and jest.

We will cover

  • How to write effective tests for your react components
  • Mocking API calls
  • How to test Redux connected component
  • Testing custom hooks

Why write tests?

The main reason we write tests is to prevent bugs, keep code clean and maintainable. Testing might seem like extra work at first. Why write tests when you could be delivering features for your application? Writing tests may seem like unproductive work that doesn’t add any immediate value to your project. However, writing effective tests ensures the delivery of well maintained, bug-free code. If you don’t write tests there’s a good chance that you will deliver bugs and as the product grows you will spend more and more time fixing these bugs. Therefore, choosing to write automated tests is a worthwhile investment.

Don’t get too excited though. Tests are really a double-edged sword. You can very well end up wasting a lot of time (and money of course) writing tests that have absolutely no value. An effective well-written test ensures application quality and maintainability. Whereas a bad tests is just a waste of time and resource that doesn’t provide any value. An effective test ensures how the application (or a component of the application) should behave form a user’s perspective. It doesn’t test the implementation details from a programmer’s perspective. If you are writing tests to verify implantation details you are wasting valuable time and the test coverage you have is nothing but a false sense of security.

Testing React Apps

We will be using the react-testing-library for this tutorial. This library is specifically designed to test application behavior and avoid testing implementation. You can also use libraries like enzymes to do this. However, as you will see react-testing-library is a relatively easy framework to use and it comes pre-packaged with create-react-app.
You can find the full docs for react-testing-library here

Let’s test our first component. Below we have a sample form. The form has two fields Name and Age. One is a text field and the other is a number field (only accepts numeric value). Additionally, our submit button is disabled when the name is empty.

We also have couple handler functions to update and submit the form. Now let’s write some test for it.


In the test case above as you can see we are testing the behavior of the app from the user’s perspective. We care about what’s in the DOM. Which DOM elements the user can interact with and so on.
For instance, the user should see the submit button disabled when the Name field is empty. We can write a test for it like below.

We are using the fireEvent from react-testing-library here to mock the DOM event. In line 4 we are using the change function to change the Name field. When the name field is empty we expect the submit button to be disabled.

Debugging Tests

At any point, if we want to inspect a DOM node we can do that easily with the debug function of the testing library. Here’s an example

We called the debug function in line 7 before we changed the input and then we called it again in line 9. In our terminal when we run npm run test we will see the following.

Example of running tests

Example of running tests

As you can see in the first instance the submit button was disabled and in the second instance, the button was not disabled.

Mocking API Requests

Let’s see how we can unit test a react component that is making API calls. The tricky part here is to mock the API request/response. We don’t want to make any API calls from our test code. There are two reasons for this.

  1. API calls are slow and it will make our tests run slower. Moreover, we don’t want to use up our backend resources by making API requests from the test code.
  2. API responses can be unpredictable. The backend we are calling may respond with unpredictable data. If something changes in the backed our tests will start to fail. Our frontend will be tightly coupled with backend implementation.

First, let’s take a look at the component we are testing.



Here we have a simple form that makes a POST call on submit. Once we get back a response we change the header of the page with a message. Let’s create a test for this.

Let’s go over the code. First of all notice how in this test we are calling jest.mock function on line 7. This will create mocks for our API calls. In line 10 we are defining what the mock response for postProducts will be. Then we mimic the user behavior of submitting a post. On lines 16 and 17 we make sure that the API call has been made once when the form is submitted with the correct input value. Now you might be wondering what’s happening in line 18. Well react will give us a warning. After the promise resolved in the component react tries to update that component (line 14 of Form.js file). Since the component state has changed react will warn us that maybe there is something missing. However, since we mocked the api call we can use the wait function that comes with the testing library.

Testing a Redux Component

Let’s take a look at how we can test a Redux component. First, let’s start with an application that has a Redux setup. Below I have a setup a very basic Redux application.

P.S. If you are interested in how to setup a redux application we have a comprehensive guide to Redux that you can find in this link.

For the purpose of this tutorial, the Redux application we are using is a bare bone and taken from Redux documentation site.

We have to set up a simple store like below

And we need a reducer like below

We have a simple counter component that is connected to Redux. Here’s how the code looks for the Counter component.

We are all set with the code. Now let’s write a test for this Counter component. Let’s take a look at the code below.

As you can see above we are wrapping our Counter component with a Redux provider. We also passed our store as a prop in the provider. Notice that, this setup allows us to not only test the component but also the store. We are testing the whole integration of React Redux flow here. This is what makes this test effective. If these tests pass we can confidently say that our component integration is in fact working. As we introduce new features and start reusing our components and if any of these tests break, then we would be able to tell that something is wrong with the new features that we wrote. This way existing tests will prevent buggy code from getting into production. Moreover, if we decide to switch from Redux to some other state management tool such as MobX, we would require a minimal amount of changes.

How to test a custom hook?

Hooks are quite an amazing feature of the React ecosystem. Hooks enable the sharing of code logic among multiple components. Let’s take a look at how we can test our hooks with react-testing-library.

Here’s a custom hook that we are going to test.

The react-testing-library makes it really easy to test these custom hooks. Let’s create a new test file for this hook.

Notice that from lines 7 to 10 we are creating a new Test component.  We plug our custom hook in the test component and check its behavior. Simple and easy.

If you would like to dive deeper into testing custom hooks I suggest you read this article by Kent C Dodds about testing custom hooks

And that’s a wrap. I hope this article was useful. Hopefully, this post will help get started on writing your own effective tests and delivering react apps with confidence. For more articles like this one please subscribe to our new letter. Until next time

About the author

Stay Informed

It's important to keep up
with industry - subscribe!

Stay Informed

Looks good!
Please enter the correct name.
Please enter the correct email.
Looks good!

Related articles

Build Real-World React Native App #11 : Pay For Remove Ads

In this chapter, we are going to apply it in order to implement the Remove Ads feature. First, we are going to implement the Remove ads screen which ...

An Introduction to Finite State Machines: Simplifying React State Management with State Machines

State machines are one of the oldest concepts in computer science but also one of the most useful. When combined together with React, they can ...

Build Real-World React Native App #10 : Setup in-App Purchase in iOS

The most awaited and considerably the lengthiest chapter is here. In this chapter, we will learn how to add the in-app purchase service in React ...

No comments yet

Sign in

Forgot password?

Or use a social network account


By Signing In \ Signing Up, you agree to our privacy policy

Password recovery

You can also try to

Or use a social network account


By Signing In \ Signing Up, you agree to our privacy policy