How to Use Jest for Testing React Components: A Step-by-Step Guide

Jest is a powerful testing framework that works seamlessly with React. Combined with React Testing Library, it lets you test component behavior without diving into implementation details. This guide walks through the essential steps to get started.

First, ensure Jest is installed. If you used Create React App, Jest comes pre-configured. For manual setup, run npm install --save-dev jest @testing-library/react. Create a jest.config.js file if needed, and add a "test": "jest" script to your package.json.

Article illustration

1. Writing Your First Component Test

Create a file named Button.test.js next to your Button.jsx component. Use render from React Testing Library and screen to query elements.

  • Import React and the test utilities: import { render, screen } from '@testing-library/react';
  • Write a test using describe and it (or test):
import Button from './Button';
test('renders button with text', () => {
  render(<Button label="Click Me" />);
  expect(screen.getByText(/click me/i)).toBeInTheDocument();
});

2. Testing User Interactions

Simulate events using fireEvent or userEvent from React Testing Library.

  • Install userEvent (optional but recommended): npm install --save-dev @testing-library/user-event
  • Example checking a click handler:
import userEvent from '@testing-library/user-event';
test('calls onClick when clicked', async () => {
  const handleClick = jest.fn();
  render(<Button onClick={handleClick} />);
  await userEvent.click(screen.getByRole('button'));
  expect(handleClick).toHaveBeenCalledTimes(1);
});

3. Snapshot Testing for UI Consistency

Snapshot tests capture the rendered output and compare it over time.

  • Use react-test-renderer: npm install --save-dev react-test-renderer
  • Write a snapshot test:
import renderer from 'react-test-renderer';
test('matches snapshot', () => {
  const tree = renderer.create(<Button label="Submit" />).toJSON();
  expect(tree).toMatchSnapshot();
});

When the component changes intentionally, update snapshots by running jest --updateSnapshot.

4. Testing Asynchronous Components

For components that fetch data, use waitFor or findBy queries.

import { waitFor } from '@testing-library/react';
test('loads and displays data', async () => {
  render(<DataComponent />);
  expect(await screen.findByText(/loaded/i)).toBeInTheDocument();
});

Jest makes React testing straightforward. Start with simple render tests, move to interactions, and add snapshots for regression protection. Keep your tests focused on user behavior, not implementation details.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *