Testing React Component’s State
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.