...

/

Writing a Component Test with React Testing Library

Writing a Component Test with React Testing Library

Learn how to refactor the component test that was implemented in the last lesson to produce robust tests using React Testing Library.

Refactoring the component test

The starter project for this lesson is the project we finished in the last lesson. It contains a test on an ErrorMessage component that verifies that the value of the message prop is rendered correctly.

The starter project was created by Create React App. So, along with Jest, React Testing Library is already installed and configured.

The starter code is available in the code widget below:

SKIP_PREFLIGHT_CHECK=true
Incomplete code

Let’s refactor the test in ErrorMessage.test.js. We’ll start by removing the import statements for the render and act functions and replacing them with the following import statement:

import { render, screen } from "@testing-library/react";

We’ll use the render function from React Testing Library rather than the one in React. This will simplify the code we write to render the component. We’ll learn more about render later in this course.

The screen object contains useful methods to select the element we want to check.

Now we can ...