Setting up Unit Tests for React Components with React Testing Library and Jest

Setting up Unit Tests for React Components with React Testing Library and Jest


2 min read

  1. 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
  1. 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';
  1. 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');

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.

  1. 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! ๐Ÿ˜Š

Did you find this article valuable?

Support Edwin Valerio by becoming a sponsor. Any amount is appreciated!