Testing React components

Testing React components

Frontend unit tests must treat the test subject, our React Component / page as a black box just like how an end user might. The closer the testing is to how a real user would interact with the app, higher the confidence we get when it is all green :)

As usual, opinions are personal and may contain some bias.

Over the years I found a common recurring pattern wherein React component tests are done by asserting on the internal behaviour of the function rather than the actual output.

Frontend unit tests must treat the test subject, our React Component as a black box just like how an end user might. For example, when I am filtering apartments in Airbnb, I only care about the information I see on the screen and how it reacts to the filters I apply. At no point do I need to know if the underlying React component state has updated or if the text is an h2 or bold.

2 popular ways I know of, using which we can unit test React components:

  1. Enzyme
  2. React Testing Library

TL;DR I would use React Testing Library approach for writing meaningful unit tests.


What are we testing?

Here, how we render the joke is an implementation detail. The fact that the joke gets fetched and rendered on click of the button is the behavior.

For example, later on we could render the joke inside a <p/> tag. The behavior of the component would remain unchanged and as such we should not have to touch our tests for this change.

Enzyme test

Here, you will see we are extracting text content of the <h3/> element using wrapper.find('h3').text(). So based on our contrived example above, if we were to convert the <h3/> into a <p/>, our test will break. For a larger, more complex component, the changes will increase exponentially. This makes refactors hard.

React Testing Library Test

Here, we are only testing for the behavior. So, as long as the behavior stays same, an update in how we render the joke for this case makes no difference. For larger projects with lot more complexity, passing tests across refactors will give developers confidence and help them move fast.

Full repo here

https://github.com/rohanBagchi/devto-testing

Thank you for reading this far.