Unit testing using Jest and React Testing LibraryUnit testing using Jest and React Testing Library

Unit testing using Jest and React Testing Library

In front-end development, unit tests are an important lifeline for ensuring code quality and safely performing refactoring. We will explain the basic usage and testing concepts of “Jest” and “React Testing Library (RTL),” which are currently the most standard combination for testing React applications.

Role of Jest and React Testing Library

These two libraries have different roles.

  • Jest: A test runner and framework for making assertions (verifying results) and mocking (faking the behavior of functions). Run the test and determine whether it achieved the expected results.
  • React Testing Library (RTL): A library that renders React components into a virtual DOM and allows users to retrieve and manipulate elements in the same way as they would in a browser.

Basic idea when writing tests

The biggest feature of RTL is the philosophy of testing user behavior, not component implementation details. It is recommended to write tests from the user’s perspective that ask, “Will this text be displayed on the screen when a button is clicked?” rather than what the contents of the state are.

Basic test implementation example

Below is an example of testing a simple component that increments a count when a button is clicked.

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import Counter from './Counter';

describe('Counterコンポーネント', () => {
  test('初期状態でカウントが0表示されていること', () => {
    // 1. コンポーネントをレンダリング
    render(<Counter />);

    // 2. 要素の取得と検証
    const countText = screen.getByText('Count: 0');
    expect(countText).toBeInTheDocument();
  });

  test('ボタンをクリックするとカウントが1増えること', async () => {
    const user = userEvent.setup();
    render(<Counter />);

    // 1. ボタン要素を取得
    const button = screen.getByRole('button', { name: 'Increment' });

    // 2. ユーザー操作(クリック)をシミュレート
    await user.click(button);

    // 3. 結果の検証
    expect(screen.getByText('Count: 1')).toBeInTheDocument();
  });
});

Points

  • Use screen.getByRole and screen.getByText to retrieve elements based on what the user actually sees (text, accessibility tree).
  • For simulating user interactions, it is best practice to use userEvent, which is more similar to actual browser behavior than fireEvent.

Summary

By combining Jest and React Testing Library, you can write robust tests from the user’s perspective. At first, you may feel like it’s a waste of time to write tests, but in the long run, it becomes a powerful ally that helps you discover bugs faster and speed up development. Let’s start by adding tests little by little, starting with the important UI that is easy to break.