testing-strategies について
ソフトウェア開発者向けのテスト実践ガイドです。テストの段階や手法、よくある落とし穴を例と検証ルールとともにまとめています。
主な機能
- 01テストピラミッドの指針
- 02ユニット・統合・E2Eのパターン
- 03TDDと再利用可能なテストデータ
- 04カバレッジ指標とJest設定
- 05落とし穴の確認とテスト検証
活用シーン
- 01テスト種別の配分検討
- 02APIやデータベースのテスト設計
- 03不安定または誤検知するテストの調査
- 04テストファイルのよくある誤りの確認
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ miles990/ claude-software-skills --skill testing-strategiesインストール後、Claude Code で/testing-strategiesを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
templates/jest.config.tspytest.iniREADME.mdvitest.config.ts詳細
テスト戦略
概要
信頼性の高いソフトウェアを構築するためのテストピラミッド、パターン、実践方法です。
テストピラミッド
/\
/ \
/ E2E\ Few, slow, expensive
/──────\
/ \
/Integration\ Some, medium speed
/──────────────\
/ \
/ Unit Tests \ Many, fast, cheap
/____________________\
| レベル | 速度 | 範囲 | 数量 |
|---|---|---|---|
| 単体 | 高速(ms) | 単一の関数/クラス | 多い(70%) |
| 結合 | 中速(s) | 複数のコンポーネント | いくらか(20%) |
| E2E | 低速(min) | システム全体 | 少ない(10%) |
単体テスト
構成:準備・実行・検証
describe('calculateDiscount', () => {
it('applies 10% discount for orders over $100', () => {
// Arrange
const order = { items: [{ price: 150 }] };
const discountService = new DiscountService();
// Act
const result = discountService.calculateDiscount(order);
// Assert
expect(result).toBe(15);
});
it('returns 0 for orders under $100', () => {
// Arrange
const order = { items: [{ price: 50 }] };
const discountService = new DiscountService();
// Act
const result = discountService.calculateDiscount(order);
// Assert
expect(result).toBe(0);
});
});
モック
// Mock dependencies
const mockEmailService = {
send: jest.fn().mockResolvedValue({ success: true })
};
const mockUserRepo = {
findById: jest.fn().mockResolvedValue({ id: '1', email: '[email protected]' })
};
describe('NotificationService', () => {
let service: NotificationService;
beforeEach(() => {
jest.clearAllMocks();
service = new NotificationService(mockEmailService, mockUserRepo);
});
it('sends email to user', async () => {
await service.notifyUser('1', 'Hello!');
expect(mockUserRepo.findById).toHaveBeenCalledWith('1');
expect(mockEmailService.send).toHaveBeenCalledWith(
'[email protected]',
'Hello!'
);
});
it('throws when user not found', async () => {
mockUserRepo.findById.mockResolvedValue(null);
await expect(service.notifyUser('999', 'Hello!'))
.rejects.toThrow('User not found');
});
});
エッジケースのテスト
describe('parseAge', () => {
// Happy path
it('parses valid age string', () => {
expect(parseAge('25')).toBe(25);
});
// Edge cases
it('handles zero', () => {
expect(parseAge('0')).toBe(0);
});
it('handles boundary values', () => {
expect(parseAge('1')).toBe(1);
expect(parseAge('150')).toBe(150);
});
// Error cases
it('throws on negative numbers', () => {
expect(() => parseAge('-5')).toThrow('Age cannot be negative');
});
it('throws on non-numeric input', () => {
expect(() => parseAge('abc')).toThrow('Invalid age format');
});
it('throws on empty string', () => {
expect(() => parseAge('')).toThrow('Age is required');
});
// Null/undefined
it('throws on null', () => {
expect(() => parseAge(null as any)).toThrow();
});
});
結合テスト
API テスト
import request from 'supertest';
import { app } from '../app';
import { db } from '../database';
describe('POST /api/users', () => {
beforeEach(async () => {
await db.users.deleteMany({});
});
afterAll(async () => {
await db.disconnect();
});
it('creates a new user', async () => {
const response = await request(app)
.post('/api/users')
.send({
email: '[email protected]',
name: 'Test User'
})
.expect(201);
expect(response.body).toMatchObject({
id: expect.any(String),
email: '[email protected]',
name: 'Test User'
});
// Verify in database
const user = await db.users.findOne({ email: '[email protected]' });
expect(user).not.toBeNull();
});
it('returns 400 for invalid email', async () => {
const response = await request(app)
.post('/api/users')
.send({
email: 'invalid-email',
name: 'Test User'
})
.expect(400);
expect(response.body.error).toBe('Invalid email format');
});
it('returns 409 for duplicate email', async () => {
// Create first user
await request(app)
.post('/api/users')
.send({ email: '[email protected]', name: 'First' });
// Try to create duplicate
const response = await request(app)
.post('/api/users')
.send({ email: '[email protected]', name: 'Second' })
.expect(409);
expect(response.body.error).toBe('Email already exists');
});
});
Testcontainers によるデータベーステスト
import { PostgreSqlContainer } from '@testcontainers/postgresql';
import { Pool } from 'pg';
describe('UserRepository', () => {
let container: StartedPostgreSqlContainer;
let pool: Pool;
let repo: UserRepository;
beforeAll(async () => {
container = await new PostgreSqlContainer().start();
pool = new Pool({ connectionString: container.getConnectionUri() });
await runMigrations(pool);
repo = new UserRepository(pool);
}, 60000);
afterAll(async () => {
await pool.end();
await container.stop();
});
beforeEach(async () => {
await pool.query('TRUNCATE users CASCADE');
});
it('creates and retrieves user', async () => {
const created = await repo.create({
email: '[email protected]',
name: 'Test'
});
const found = await repo.findById(created.id);
expect(found).toEqual(created);
});
});
E2E テスト
Playwright
import { test, expect } from '@playwright/test';
test.describe('User Authentication', () => {
test('successful login flow', async ({ page }) => {
await page.goto('/login');
// Fill form
await page.fill('[data-testid="email-input"]', '[email protected]');
await page.fill('[data-testid="password-input"]', 'password123');
// Submit
await page.click('[data-testid="login-button"]');
// Verify redirect to dashboard
await expect(page).toHaveURL('/dashboard');
await expect(page.locator('[data-testid="welcome-message"]'))
.toContainText('Welcome, [email protected]');
});
test('shows error for invalid credentials', async ({ page }) => {
await page.goto('/login');
await page.fill('[data-testid="email-input"]', '[email protected]');
await page.fill('[data-testid="password-input"]', 'wrongpassword');
await page.click('[data-testid="login-button"]');
await expect(page.locator('[data-testid="error-message"]'))
.toBeVisible()
.toContainText('Invalid credentials');
});
});
test.describe('Shopping Cart', () => {
test('add item and checkout', async ({ page }) => {
// Setup - login
await page.goto('/login');
await page.fill('[data-testid="email-input"]', '[email protected]');
await page.fill('[data-testid="password-input"]', 'password');
await page.click('[data-testid="login-button"]');
// Browse products
await page.goto('/products');
await page.click('[data-testid="product-1"] [data-testid="add-to-cart"]');
// Verify cart
await expect(page.locator('[data-testid="cart-count"]')).toHaveText('1');
// Checkout
await page.click('[data-testid="cart-icon"]');
await page.click('[data-testid="checkout-button"]');
// Fill shipping
await page.fill('[data-testid="address"]', '123 Test St');
await page.click('[data-testid="place-order"]');
// Verify success
await expect(page).toHaveURL(/\/orders\/\d+/);
await expect(page.locator('[data-testid="order-status"]'))
.toContainText('Order Confirmed');
});
});
ビジュアルリグレッションテスト
import { test, expect } from '@playwright/test';
test('homepage visual regression', async ({ page }) => {
await page.goto('/');
// Wait for dynamic content
await page.waitForSelector('[data-testid="hero-section"]');
// Take screenshot and compare
await expect(page).toHaveScreenshot('homepage.png', {
maxDiffPixels: 100,
threshold: 0.2
});
});
test('responsive design', async ({ page }) => {
await page.setViewportSize({ width: 375, height: 667 }); // iPhone SE
await page.goto('/');
await expect(page).toHaveScreenshot('homepage-mobile.png');
});
テスト駆動開発(TDD)
レッド・グリーン・リファクターサイクル
// 1. RED - Write failing test first
test('passwordValidator rejects passwords without numbers', () => {
const result = validatePassword('NoNumbers!');
expect(result.valid).toBe(false);
expect(result.errors).toContain('Must contain at least one number');
});
// 2. GREEN - Write minimal code to pass
function validatePassword(password: string): ValidationResult {
const errors: string[] = [];
if (!/\d/.test(password)) {
errors.push('Must contain at least one number');
}
return { valid: errors.length === 0, errors };
}
// 3. REFACTOR - Improve code quality
const VALIDATION_RULES = [
{ pattern: /\d/, message: 'Must contain at least one number' },
{ pattern: /[A-Z]/, message: 'Must contain at least one uppercase letter' },
{ pattern: /[a-z]/, message: 'Must contain at least one lowercase letter' },
{ pattern: /.{8,}/, message: 'Must be at least 8 characters' }
];
function validatePassword(password: string): ValidationResult {
const errors = VALIDATION_RULES
.filter(rule => !rule.pattern.test(password))
.map(rule => rule.message);
return { valid: errors.length === 0, errors };
}
テストパターン
テストフィクスチャ
// fixtures/users.ts
export const validUser = {
email: '[email protected]',
name: 'Test User',
role: 'user'
};
export const adminUser = {
...validUser,
role: 'admin',
email: '[email protected]'
};
// In tests
import { validUser, adminUser } from '../fixtures/users';
describe('UserService', () => {
it('creates user with valid data', async () => {
const result = await service.create(validUser);
expect(result.email).toBe(validUser.email);
});
});
ファクトリー関数
// factories/user.factory.ts
import { faker } from '@faker-js/faker';
export function createUser(overrides: Partial<User> = {}): User {
return {
id: faker.string.uuid(),
email: faker.internet.email(),
name: faker.person.fullName(),
createdAt: faker.date.past(),
...overrides
};
}
// In tests
it('handles users with long names', () => {
const user = createUser({ name: 'A'.repeat(100) });
const result = formatUserCard(user);
expect(result.displayName).toHaveLength(50); // Truncated
});
非同期コードのテスト
// Async/await
it('fetches user data', async () => {
const user = await userService.getById('123');
expect(user.name).toBe('John');
});
// Promises
it('fetches user data', () => {
return userService.getById('123').then(user => {
expect(user.name).toBe('John');
});
});
// Testing rejected promises
it('throws on invalid id', async () => {
await expect(userService.getById('invalid'))
.rejects.toThrow('User not found');
});
// Waiting for side effects
it('debounces search input', async () => {
const onSearch = jest.fn();
render(<SearchBox onSearch={onSearch} debounceMs={300} />);
await userEvent.type(screen.getByRole('textbox'), 'test');
// Should not have called yet
expect(onSearch).not.toHaveBeenCalled();
// Wait for debounce
await waitFor(() => {
expect(onSearch).toHaveBeenCalledWith('test');
}, { timeout: 500 });
});
コードカバレッジ
カバレッジ指標
| 指標 | 測定内容 |
|---|---|
| 行 | 実行された行の割合 |
| 分岐 | 実行された if/else 分岐の割合 |
| 関数 | 呼び出された関数の割合 |
| ステートメント | 実行されたステートメントの割合 |
Jest の設定
// jest.config.js
module.exports = {
collectCoverageFrom: [
'src/**/*.{ts,tsx}',
'!src/**/*.d.ts',
'!src/**/*.stories.tsx',
'!src/test/**'
],
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80
}
}
};
関連スキル
- [[code-quality]] - テスト可能なコードの作成
- [[devops-cicd]] - CI との統合
- [[performance-optimization]] - パフォーマンステスト
落とし穴
テストで最もよくある、代償の大きいミスです
SE-1: 振る舞いではなく実装をテストする
- 重大度: 高
- 状況: テストが内部実装と強く結び付いており、リファクタリング時にすべてのテストが壊れます
- 原因: プライベートメソッドのテスト、細かすぎるモック、内部状態の検証
- 症状:
- コードを1行変更しただけで、10件のテストが失敗する
- テストファイルがコードより長い
- リファクタリング時にテストの修正により多くの時間がかかる
- 検出:
expect.*\.toHaveBeenCalledTimes\(\d{2,}\)|mock.*private|spy.*internal - 解決策: 公開 API/振る舞いをテストし、ブラックボックステストを使用し、モックの数を減らします
SE-2: 偽陽性テスト(False Positive)
- 重大度: 致命的
- 状況: テストは常に通過しますが、実際には何も検証していません
- 原因: await の付け忘れ、expect が実行されていない、条件判定の誤り
- 症状:
- テストは通過してもバグが残っている
- テスト内の重要な assertion を削除してもテストが通過する
- カバレッジは高いのに信頼性が低い
- 検出:
it\(.*\{\s*\}|expect\(.*\)(?!\.)|\.resolves(?!\.)|\.rejects(?!\.) - 解決策: TDD(まず失敗するテストを書く)、テストコードのレビュー、ESLint no-floating-promises の使用
SE-3: 不安定なテスト(Flaky Tests)
- 重大度: 高
- 状況: コードを変更していないのに、テストが通過したり失敗したりします
- 原因: 時間や外部サービスへの依存、競合状態、共有状態
- 症状:
- CI で通過するまで再試行が必要
- ローカルでは通過するが、CI では失敗する
- チームが失敗するテストを無視し始める
- 検出:
new Date\(\)|Date\.now\(\)|setTimeout.*\d{4,}|sleep\(\d+\) - 解決策: フェイクタイマーを使用し、テストの状態を分離し、ハードコードされた遅延を避け、外部依存関係をモックします
SE-4: テストピラミッドの逆転
- 重大度: 中
- 状況: E2E テストが多すぎて単体テストが少なく、CI が非常に遅くなります
- 原因: 「E2E テストのほうが実際の環境に近い」という誤解、単体テストを書きたくないという考え
- 症状:
- CI の実行に30分以上かかる
- テスト失敗の原因を特定しにくい
- E2E テストが頻繁に不安定になる
- 検出:
describe.*E2E|playwright.*test|cypress.*it(単体テストの数を大幅に超えている) - 解決策: 単体70%/結合20%/E2E 10%の割合に従い、E2E では重要な経路のみをテストします
SE-5: 過剰なモック
- 重大度: 中
- 状況: モックが多すぎてテストの意味が失われ、モック自体をテストしているだけになります
- 原因: 分離のためにすべての依存関係をモックする、テスト実行時間への不安
- 症状:
- テストは通過するが、統合時に失敗する
- モックの動作が実際の動作と一致しない
- 依存関係を更新した後、モックが古くなる
- 検出:
jest\.mock.*jest\.mock.*jest\.mock|mock\(.*\).*mock\(.*\).*mock\( - 解決策: 外部依存関係(ネットワーク、ファイルシステム)のみをモックし、実際のインメモリ実装を使用し、結合テストを増やします
検証
V-1: 空のテストを禁止
- 種類: 正規表現
- 重大度: 致命的
- パターン:
(it|test)\s*\([^)]+,\s*(async\s*)?\(\)\s*=>\s*\{\s*\}\s*\) - メッセージ: 空のテストが検出されました。テストに assertion がありません
- 修正の提案: expect() で意味のある assertion を追加してください
- 対象:
*.test.ts,*.test.js,*.spec.ts,*.spec.js
V-2: テストに assertion がない
- 種類: 正規表現
- 重大度: 高
- パターン:
(it|test)\s*\([^)]+,\s*(async\s*)?\(\)\s*=>\s*\{[^}]*\}(?![^}]*expect) - メッセージ: expect() による assertion がないテストは、偽陽性の可能性があります
- 修正の提案: expect() による assertion を少なくとも1つ追加してください
- 対象:
*.test.ts,*.test.js,*.spec.ts,*.spec.js
V-3: fit/fdescribe(フォーカスされたテスト)を禁止
- 種類: 正規表現
- 重大度: 致命的
- パターン:
\b(fit|fdescribe|it\.only|describe\.only|test\.only)\s*\( - メッセージ: フォーカスされたテストにより、CI でほかのテストがスキップされます
- 修正の提案: コミット前に
f接頭辞または.onlyを削除してください - 対象:
*.test.ts,*.test.js,*.spec.ts,*.spec.js
V-4: 説明なしの skip tests を禁止
- タイプ: regex
- 重要度: medium
- パターン:
(xit|xdescribe|it\.skip|describe\.skip|test\.skip)\s*\([^)]+\) - メッセージ: Skipped test without documented reason
- 修正提案: Add comment explaining why test is skipped and tracking issue
- 対象:
*.test.ts,*.test.js,*.spec.ts,*.spec.js
V-5: テストでの setTimeout の使用
- タイプ: regex
- 重要度: high
- パターン:
setTimeout\s*\(\s*[^,]+,\s*\d{3,}\s*\) - メッセージ: Hard-coded delays in tests cause flakiness and slow tests
- 修正提案: Use
jest.useFakeTimers()orwaitFor()from testing-library - 対象:
*.test.ts,*.test.js,*.spec.ts,*.spec.js
コメント
Markdown 対応