Testing React Components
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 ‘setupFiles’:
Let’s create a little example test using the newly added library. If you haven’t done 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
Edit this page on GitHub