「テスト書いた方がいいのは分かるけど、何から始めれば?」と悩んでいませんか?
現役WEBエンジニアとして、テスト駆動開発を行っています。
この記事では、テストの基本を解説します。
目次
テストの種類
テストピラミッド
| 種類 | 対象 | 速度 | 量 |
|---|---|---|---|
| 単体 | 関数・クラス | 速い | 多 |
| 結合 | コンポーネント間 | 普通 | 中 |
| E2E | システム全体 | 遅い | 少 |
まず単体テストから
- 書きやすい
- 実行が速い
- 問題の特定が容易
Jest基本
セットアップ
npm install -D jest
テストファイル
// sum.js
function sum(a, b) {
return a + b;
}
module.exports = sum;
// sum.test.js
const sum = require('./sum');
test('1 + 2 = 3', () => {
expect(sum(1, 2)).toBe(3);
});
実行
npx jest
# または
npm test
基本的なマッチャー
よく使うもの
// 等価
expect(value).toBe(3);
expect(obj).toEqual({ a: 1 });
// 真偽値
expect(flag).toBeTruthy();
expect(flag).toBeFalsy();
// null/undefined
expect(value).toBeNull();
expect(value).toBeUndefined();
expect(value).toBeDefined();
// 数値
expect(num).toBeGreaterThan(3);
expect(num).toBeLessThan(5);
// 配列・文字列
expect(arr).toContain('item');
expect(str).toMatch(/pattern/);
// 例外
expect(() => fn()).toThrow('error');
非同期テスト
async/await
test('fetchUser', async () => {
const user = await fetchUser(1);
expect(user.name).toBe('田中');
});
Promise
test('fetchUser', () => {
return fetchUser(1).then(user => {
expect(user.name).toBe('田中');
});
});
モック
関数のモック
const mockFn = jest.fn();
mockFn.mockReturnValue(42);
expect(mockFn()).toBe(42);
expect(mockFn).toHaveBeenCalled();
モジュールのモック
jest.mock('./api');
const api = require('./api');
api.fetchUser.mockResolvedValue({ name: '田中' });
React テスト
React Testing Library
import { render, screen, fireEvent } from '@testing-library/react';
import Counter from './Counter';
test('カウントアップ', () => {
render(<Counter />);
// 初期値確認
expect(screen.getByText('Count: 0')).toBeInTheDocument();
// クリック
fireEvent.click(screen.getByText('+1'));
// 更新確認
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
テストを書くコツ
AAA パターン
test('ユーザー作成', () => {
// Arrange(準備)
const userData = { name: '田中' };
// Act(実行)
const user = createUser(userData);
// Assert(検証)
expect(user.name).toBe('田中');
});
何をテストするか
| テストする | テストしない |
|---|---|
| ビジネスロジック | ライブラリ |
| 境界値 | 外部API(モック) |
| エラーケース | 単純なgetter |
まとめ
テスト入門のポイント:
- 単体テストから始める
- Jestを使う
- AAAパターン
- 重要な部分からテスト
