The many ways to test React components

The main ways to test React components are by using one of the following libraries:

What should I choose? It depends in what you are trying to accomplish, these libraries differ in both technical implementations and philosoph.

react-test-renderer

react-test-renderer focuses on testing the representation of a React application tree and is not tied to any particular environment. While this allows making assertions without depending on the DOM or other native environments, the surface of uses for a normal React web-app is very small. For instance: it's impossible to test user interaction and events.

Enzyme

Enzyme has been the de-facto standard for Component testing for years, it provides ways to test components in isolation and make expectations on the internal states of components and prop passing. While very powerful, the provided APIs are so much to become easily overwhelming to even test the simplest cases.
In many cases, testing the internals of the components had the side effect of making tests very fragile, subjective, and with high cost of tests maintenance. At the time of writing, it looks like the community is slowly moving toward testing the end result of React components rather than their internal implementation.

React Test Utilities

react-dom/test-utils offers a set of utilities to interact with the DOM generated by ReactDOM, allowing to test the closest thing to the user, the HTML generated by ReactDOM.

React Testing Library

react-testing-library is based on ReactDOM and is focused on testing the generated markup instead of the component internals. In this course we will focus on using this library as we share the values and principle it is based upon "test your program as close as how your user would".

Other technique worth mentioning

Shallow rendering

Shallow rendering is a partial render of a component (his children are not rendered).

Snapshot testing

Snapshot testing (not to be confused with screenshot testing) is a technique based on saving to a file the result of a test the first time it runs (the generated HTML for React Components) and for every consequent run, the new result is compared to the previous one saved in the file as a text diff.

Can we use different testing tools in the same project?

Yes, they serve different purposes and can even be used together in the same file.

Author: Jaga Santagostino

results matching ""

    No results matching ""