Testing React Components
The recommended testing framework is Jest. This guide assumes that you followed the Unit testing guide to set up Jest.
The @testing-library/react by Kent C. Dodds has risen in popularity since its release and is a great replacement for enzyme. You can write unit and integration tests and it encourages you to query the DOM in the same way the user would. Hence the guiding principle:
The more your tests resemble the way your software is used, the more confidence they can give you.
It provides light utility functions on top of react-dom
and react-dom/test-utils
and gives you the confidence that refactors of your component in regards to the implementation (but not functionality) don’t break your tests.
Installation
Install the library as one of your project’s devDependencies
. Optionally you may install jest-dom
to use its custom jest matchers.
If you are using Jest 28, you also need to install jest-environment-jsdom
:
Create the file setup-test-env.js
at the root of your project. Insert this code into it:
This file gets run automatically by Jest before every test and therefore you don’t need to add the imports to every single test file.
Lastly you need to tell Jest where to find this file. Open your jest.config.js
and add this entry to the bottom after ‘setupFiles’:
Note: The Jest 27 configuration
testEnvironment
default value changed tonode
, you need to change it tojsdom
for React Testing Library to work properly
Usage
Let’s create a little example test using the newly added library. If you haven’t done so already, read the unit testing guide — essentially you’ll use @testing-library/react
instead of react-test-renderer
now. There are a lot of options when it comes to selectors, this example chooses getByTestId
here. It also utilizes toHaveTextContent
from jest-dom
: