Installing RTL and Configuring Jest for Component Testing
Understand how to install React Testing Library and configure Jest for component testing. Learn to set up jest-dom for useful DOM matchers and mock CSS and image imports to ensure smooth test runs without style or asset errors.
Understanding the starter project
Setting up React is beyond the scope of this course. So, React, Babel, Webpack, and several plugins have been installed and configured in the starter project. The setup is very basic, but it is sufficient for this lesson.
We have already learned how to install Jest. So, Jest is also installed in the starter project.
If we look at the source code files in the project, we’ll see the ErrorMessage component from the previous couple of lessons along with an ErrorMessage test.
We can run the following command to see the rendered ErrorMessage component:
npm start
.error-message {
margin: 10px;
color: red;
display: flex;
align-items: center;
}
.error-message img {
width: 25px;
margin-right: 5px;
}
Installing React Testing Library
To install React Testing Library we run the following command:
npm install --save-dev @testing-library/react
We will also install jest-dom which gives us useful matchers to use on the DOM. This includes the toBeInTheDocument matcher that our test uses.
npm install ...