Testing React Component’s State

Anthony Ng
Apr 16, 2017 · 2 min read

We unit test normal JavaScript functions to make sure they work as intended. For a certain input, it should return the correct output.

This is a good test. It tests what we care about; that we receive the correct answer. We are not concerned about the internal implementation of the sum function. Imagine if we had this contrived implementation of the sum function.

The same test we had before still works for this new implementation.

You can imagine a bad test to have tested the internal implementation of the function. Take a look at the following test:

This is a bad test because we’re testing something that we don’t care about.

This is how we should think about testing React components as well. Imagine we have this basic React Component.

In this basic component, a button will toggle its disabled state when I click the other button. A good test for this might be:

A bad test to write is to test how we are implementing this logic. In our sum function example, an implementation detail was the array we had. In our React Component example, the implementation detail is the state we are using.

Again, this is a bad test because we could refactor our Component to this:

Our component is still doing what we want, but our new test is now failing.

Remember that React components are functions. You pass it inputs (as props) and you receive an output (from its render function). The component’s state is an implementation detail.

Before you test a component’s state, step back and see if you’re testing the right thing.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store