JestとReact Testing Libraryを使ったユニットテストとスナップショットテスト

Reactアプリケーションにおいて、ユニットテストとスナップショットテストは品質を維持し、バグを未然に防ぐために重要です。JestとReact Testing Libraryは、それぞれテストランナーとUIテストライブラリとして広く使用されています。本記事では、これらのツールを活用した効果的なテスト手法について解説します。
目次
Jestとは何か?
JestはJavaScript向けのテストランナーであり、特にReactアプリケーションのテストで広く使われています。
// Jestテストの基本例
test('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3);
});
React Testing Libraryとは何か?
React Testing LibraryはReactコンポーネントのテストに特化したライブラリです。
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import App from './App';
test('renders a button', () => {
render(<App />);
expect(screen.getByRole('button')).toHaveTextContent('Click me');
});
Jestのセットアップ
JestをReactプロジェクトに導入するには、以下のコマンドを使用します。
npm install --save-dev jest @testing-library/react @testing-library/jest-dom
React Testing Libraryのセットアップ
React Testing LibraryはJestと組み合わせて使用されます。
npm install --save-dev @testing-library/react @testing-library/jest-dom
ユニットテストの基本
ユニットテストは、個々の関数やコンポーネントが期待通りに動作するかを確認します。
function sum(a, b) {
return a + b;
}
test('sum function works correctly', () => {
expect(sum(1, 2)).toBe(3);
});
コンポーネントのテスト
コンポーネントが正しくレンダリングされるかをテストします。
import { render, screen } from '@testing-library/react';
import Button from './Button';
test('Button displays correct text', () => {
render(<Button text="Click me" />);
expect(screen.getByText('Click me')).toBeInTheDocument();
});
ユーザーインタラクションのテスト
ユーザーの操作(クリック、入力など)が正しく動作するかをテストします。
import { render, fireEvent, screen } from '@testing-library/react';
import Button from './Button';
test('Button click triggers event', () => {
const handleClick = jest.fn();
render(<Button onClick={handleClick} />);
fireEvent.click(screen.getByRole('button'));
expect(handleClick).toHaveBeenCalled();
});
スナップショットテスト
コンポーネントのUIが意図せず変更されていないかを検証します。
import renderer from 'react-test-renderer';
import Button from './Button';
test('Button snapshot', () => {
const tree = renderer.create(<Button text="Click me" />).toJSON();
expect(tree).toMatchSnapshot();
});
非同期コードのテスト
APIコールや非同期処理が正しく動作するかをテストします。
import { render, screen, waitFor } from '@testing-library/react';
import FetchComponent from './FetchComponent';
test('fetches and displays data', async () => {
render(<FetchComponent />);
await waitFor(() => expect(screen.getByText('Data Loaded')).toBeInTheDocument());
});
モック関数の使用
依存関係やAPIコールをモックしてテストします。
const mockApi = jest.fn(() => Promise.resolve({ data: 'Success' }));
async function fetchData(api) {
const response = await api();
return response.data;
}
test('fetchData returns data', async () => {
const result = await fetchData(mockApi);
expect(result).toBe('Success');
});
カバレッジレポート
Jestはコードカバレッジのレポートを生成できます。
npm test -- --coverage
まとめ
JestとReact Testing Libraryを活用することで、Reactアプリケーションの品質を効率的に維持できます。ユニットテスト、スナップショットテスト、非同期テストを組み合わせることで、堅牢なテスト環境を構築できます。
-
前の記事
Railsのエラー『ActiveModel::StrictValidationFailed』の解決方法 2025.05.14
-
次の記事
kotlin Listをインデックス番号付きに変換する 2025.05.15
コメントを書く