This tutorial aims to introduce you to React Testing Library (RTL), a very useful library for testing React components. By the end of this tutorial, you will be able to write and run tests using React Testing Library.
You will learn the following:
- Basics of React Testing Library
- Writing test cases for React components
- Running and analyzing the test results
Basic knowledge of React and JavaScript is required.
React Testing Library is a simple and complete set of React DOM testing utilities that encourage good testing practices. RTL tries to test your components in a way that resembles how users would interact with your app.
You can add React Testing Library to your project by running:
npm install --save-dev @testing-library/react
Let's test a simple component Greeting
that accepts a name
prop and renders a greeting message.
// Greeting.js
import React from 'react';
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
export default Greeting;
We can test this component like this:
// Greeting.test.js
import React from 'react';
import { render, screen } from '@testing-library/react';
import Greeting from './Greeting';
test('renders greeting message', () => {
render(<Greeting name="John" />);
const linkElement = screen.getByText(/Hello, John!/i);
expect(linkElement).toBeInTheDocument();
});
In this test, we first render the Greeting
component with 'John' as the name prop. Then we use getByText
to get the element with the text 'Hello, John!'. The toBeInTheDocument
assertion checks if the element is in the document.
In this tutorial, you learned how to use the React Testing Library to write unit tests for your React components. The next step is to explore more complex scenarios and testing interactions, like clicks and form submissions.
Write a test for a Button
component that accepts a label
prop and renders a button with that label.
Write a test for a Counter
component that starts at 0, increments when a 'Increment' button is clicked, and displays the current count.
Write a test for a LoginForm
component that accepts a username and password and submits them when a 'Submit' button is clicked.
Remember, practice is the key to mastering any skill, so don't stop here. Keep writing tests for your components and soon you'll find it becoming second nature.
Happy Testing!