【React/Jest】10分内に「ざっくり」わかる!フロンドエンドの団体・結合テストの基礎
はじめに
JestはFacebookが開発したJavaScriptテストフレームワークで、Reactアプリケーションのテストを簡単に作成して実行することができます。
テスト環境の設定
プロジェクトの作成する
まず、Create React Appを使って新しいReactプロジェクトを生成します。ターミナルで次のコマンドを実行してください。
npx create-react-app react-jest-tutorial
Jestのインストール
Jestをプロジェクトに追加します。
npm install --save-dev jest
Jest設定ファイルの生成
プロジェクトルートにjest.config.jsファイルを生成して下記の内容を追加します。
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'],
// 他のJest設定オプションを追加することができます。
};
setupTestsの設定
srcフォルダ内にsetupTests.jsファイルを生成して次の内容を追加します。
import '@testing-library/jest-dom/extend-expect';
// 他のテスト環境設定を追加することができます。
単体テスト
コンポーネントとテストの作成
srcフォルダ内にExampleComponent.jsファイルを生成して次の内容を追加します。
// ExampleComponent.js
import React from 'react';
const ExampleComponent = ({ text }) => {
return <div>{text}</div>;
};
export default ExampleComponent;
次はテストファイルを作ってみましょう。 srcフォルダ内にExampleComponent.test.jsファイルを生成して次の内容を追加します。
// ExampleComponent.test.js
import React from 'react';
import { render, screen } from '@testing-library/react';
import ExampleComponent from './ExampleComponent';
test('renders text correctly', () => {
render(<ExampleComponent text="Hello, Jest!" />);
const textElement = screen.getByText(/hello, jest/i);
expect(textElement).toBeInTheDocument();
});
テストの実行
ターミナルで次のコマンドを実行してJestを使ってテストを実行します。
npm test
Jestはテストを検索して実行し、結果をターミナルに表示します。
結合テスト
結合テスト(Integration Testing)は、複数のコンポーネントやシステムが一緒に動作する方法をテストすることです。
コンポーネントの修正
ExampleComponent.js
// ExampleComponent.js
import React, { useState } from 'react';
const ExampleComponent = ({ onButtonClick }) => {
const [count, setCount] = useState(0);
const handleButtonClick = () => {
setCount(count + 1);
onButtonClick(count + 1);
};s
return (
<div>
<p>Count: {count}</p>
<button onClick={handleButtonClick}>Click me</button>
</div>
);
};
export default ExampleComponent;
コンポーネントはボタンをクリックするとカウントを増やし、onButtonClick propで渡された関数を呼び出します。
結合テストの作成
次はExampleComponent.test.jsファイルを修正して結合テストを作成します。
// ExampleComponent.test.js
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import ExampleComponent from './ExampleComponent';
test('renders component and handles button click', () => {
const mockOnButtonClick = jest.fn();
render(<ExampleComponent onButtonClick={mockOnButtonClick} />);
// 初期レンダリング確認
const countElement = screen.getByText(/count: 0/i);
expect(countElement).toBeInTheDocument();
// ボタンク押下時の動作確認
const buttonElement = screen.getByText(/Click me/i);
fireEvent.click(buttonElement);
// ステータス更新の確認
const updatedCountElement = screen.getByText(/count: 1/i);
expect(updatedCountElement).toBeInTheDocument();
// propで渡された関数が呼び出されたか確認する
expect(mockOnButtonClick).toHaveBeenCalledWith(1);
});
このテストはコンポーネントが正しくレンダリングされ、ボタンをクリックすると状態が更新され、propで渡された関数が呼び出されるかを確認します。
テストの実行
npm test
これでJestはユニットテストと結合テストの両方を実行し、結果をターミナルに表示します。
最後に
Reactアプリケーションのユニットテストと結合テストを一緒に書いて実行する方法をみてみました。 このようなテストでアプリケーションの各部分が個別でも動作し、一緒に動作するかを確認することができます。
向上心のエンジニア
ソンさん