javascript-testing-patterns は何をしますか?
Jest、Vitest、Testing Library を使用した包括的なテスト戦略(ユニットテスト、インテグレーションテスト、エンドツーエンドテスト)を実装します。モック、フィクスチャ、テスト駆動開発に対応。JavaScript/TypeScript のテスト作成、テスト基盤のセットアップ、TDD/BDD ワークフローの実装時に使用します。
概要
このスキルは、JavaScript/TypeScript プロジェクトにおけるテスト戦略全体を支援します。主要なテストフレームワーク (Jest、Vitest) と Testing Library を活用し、モックやフィクスチャを用いたテストの分離手法や、TDD/BDD の実践パターンを提供します。
主な機能
- ユニットテスト: 個々の関数やクラスのテスト
- インテグレーションテスト: モジュール間の連携テスト
- エンドツーエンドテスト: アプリケーション全体の動作確認
- モックとスタブ: 依存関係の置き換え
- フィクスチャ: テストデータの管理
- TDD/BDD ワークフロー: テスト駆動開発の流れ
サポートするプラットフォーム
- Jest: 広く使われるテストランナー
- Vitest: Vite ベースの高速テストランナー
- Testing Library: React、Vue、DOM 用のテストユーティリティ
使用方法
インストール
# Jest
npm install --save-dev jest @testing-library/react @testing-library/jest-dom
# Vitest
npm install --save-dev vitest @testing-library/react @testing-library/jest-dom
設定例
// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterSetup: ['./jest.setup.js'],
moduleNameMapper: {
'\\.(css|less|scss)$': 'identity-obj-proxy',
},
};
// vitest.config.ts
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
environment: 'jsdom',
setupFiles: ['./vitest.setup.ts'],
},
});
テスト例
// 単純なユニットテスト
import { sum } from './math';
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
// モックを使ったテスト
jest.mock('./api');
import { fetchData } from './api';
const mockData = { id: 1, name: 'Test' };
fetchData.mockResolvedValue(mockData);
test('fetches data successfully', async () => {
const data = await fetchData('/endpoint');
expect(data).toEqual(mockData);
});
// Testing Library を使った React コンポーネントのテスト
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import MyComponent from './MyComponent';
test('renders and interacts', async () => {
render(<MyComponent />);
const button = screen.getByRole('button', { name: /click me/i });
await userEvent.click(button);
expect(screen.getByText('Clicked!')).toBeInTheDocument();
});
テスト駆動開発 (TDD) のワークフロー
- 失敗するテストを書く
- テストが通る最小限のコードを実装する
- リファクタリングする
- 繰り返す
ベストプラクティス
- テストは独立して実行できるようにする
- モックは必要最小限に留める
- テストの意図が明確になるように命名する
- カバレッジレポートを活用して不足箇所を特定する