Testing Overview
You can test React components similar to testing other JavaScript code.
There are a few ways to test React components. Broadly, they divide into two categories:
Rendering component trees in a simplified test environment and asserting on their output.Running a complete app in a realistic browser environment (also known as “end-to-end” tests).
This documentation section focuses on testing strategies for the first case. While full end-to-end tests can be very useful to prevent regressions to crucial workflows, such tests are not concerned with React components in particular, and are out of the scope of this section.
Tradeoffs
When choosing testing tools, it is worth considering a few tradeoffs:
Iteration speed vs Realistic environment: Some tools offer a very fast feedback loop between making a change and seeing the result, but don’t model the browser behavior precisely. Other tools might use a real browser environment, but reduce the iteration speed and are flakier on a continuous integration server.How much to mock: With components, the distinction between a “unit” and “integration” test can be blurry. If you’re testing a form, should its test also test the buttons inside of it? Or should a button component have its own test suite? Should refactoring a button ever break the form test?
Different answers may work for different teams and products.
Recommended Tools
jsdom
. While jsdom is only an approximation of how the browser works, it is often excellent enough for testing React components. Jest provides a fantastic iteration speed combined with powerful features like mocking modules and timers so you can have more control over how the code executes.
Learn More
This section is divided in two pages:
- Recipes: Common patterns when writing tests for React components.
- Environments: What to consider when setting up a testing environment for React components.