Testing React Components
The recommended testing framework is Jest. This guide assumes that you followed the Unit testing guide to set up Jest and that you are using Jest 29 or above.
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/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.
Install the library as one of your project’s
devDependencies. Optionally you may install
jest-dom to use its custom jest matchers.
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
Please note: The
testEnvironment default is
node. If you don’t want to switch it globally you can use a
@jest-environment comment, see testEnvironment docs.
Let’s create a little example test using the newly added library. If you haven’t done so already, read the unit testing guide. There are a lot of options when it comes to selectors, this example chooses
getByTestId here. It also utilizes