Setting up Unit Tests for React Components with React Testing Library and Jest
- Install the required dependencies:
- React Testing Library: This library provides utility functions for testing React components.
npm install --save-dev react-testing-library
- Jest: This is a popular JavaScript testing framework that works well with React.
npm install --save-dev jest
- Create a file for the test and import the dependencies:
Create a file with a .test.js
extension in the same directory as the component you want to test. For example, if you want to test a component called Button
, you can create a file called Button.test.js
.
Then, import the dependencies you installed in the previous step:
import React from 'react';
import { render } from 'react-testing-library';
- Write the test:
Next, you can write the test function using the render
function from React Testing Library. The render
function returns an object that contains several utility functions for interacting with the rendered component, such as getByText
for finding elements by their text content.
Here is an example of a simple test for a Button
component:
test('button renders with the correct text', () => {
const { getByText } = render(<Button>Click me</Button>);
const buttonElement = getByText('Click me');
expect(buttonElement).toBeInTheDocument();
});
This test will render the Button
component and use the getByText
function to find the button element with the text "Click me". It will then use the expect
function from Jest to check that the element is present in the document.
- Run the test:
To run the test, you can use the jest
command in your terminal. Jest will automatically find and run all the tests in your project.
npm test
That's it! You have now set up a unit test for a React component using React Testing Library and Jest. You can write more tests by following the same pattern and using the utility functions provided by React Testing Library to interact with the rendered component.
I hope this helps! ๐
Subscribe to my newsletter
Read articles from Edwin Valerio directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Edwin Valerio
Edwin Valerio
Hey there, my name is Edwin and I'm a software engineer living in Boston. I love nothing more than sharing my knowledge and skills with others. As a full-stack developer, I know a thing or two about building amazing software from front to back. And I'm always looking for ways to make my explanations more engaging and enjoyable for everyone.