본문으로 건너뛰기
cccskills
무료GitHub에 공개

test-patterns

Guides test implementation following the test pyramid (75% unit, 20% integration, 5% E2E), Arrange-Act-Assert pattern, and project coverage thresholds (branches 70%, functions 80%, lines 80%, statements 80%). Covers test naming conventions, test independence, mock and stub patterns, test data management with fixtures and builders, and CI integration. Use when writing tests, reviewing test code, or setting up test infrastructure.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md6.9 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

テストパターンガイド

プロジェクトのテスト戦略に基づいてテストを実装・レビューするためのスキル。 TESTING.md で定義されたパターンと基準を適用する。

1. テストピラミッド

         /\
        /E2E\        (5%)  - クリティカルパス100%
       /------\
      /統合テスト\    (20%) - 60%以上カバレッジ
     /----------\
    /ユニットテスト\  (75%) - 80%以上カバレッジ
   /--------------\
テスト種別比率カバレッジ目標優先度
ユニットテスト75%80%以上高
統合テスト20%60%以上中
E2Eテスト5%クリティカルパス100%高

2. カバレッジ閾値

プロジェクトの最低カバレッジ基準:

メトリクス閾値
branches70%
functions80%
lines80%
statements80%
// jest.config.js
coverageThreshold: {
  global: {
    branches: 70,
    functions: 80,
    lines: 80,
    statements: 80
  }
}

3. テスト構造(AAA Pattern)

すべてのテストは Arrange-Act-Assert パターンに従うこと:

describe("UserService", () => {
  let service: UserService;
  let mockRepository: jest.Mocked<IUserRepository>;

  beforeEach(() => {
    // Arrange: テスト準備(各テストで新しいインスタンス)
    mockRepository = mock<IUserRepository>();
    service = new UserService(mockRepository);
  });

  describe("createUser", () => {
    it("should create user successfully with valid data", async () => {
      // Arrange
      const userData = { email: "test@example.com", name: "Test User" };
      const expectedUser = { id: "123", ...userData };
      mockRepository.save.mockResolvedValue(expectedUser);

      // Act
      const result = await service.createUser(userData);

      // Assert
      expect(result).toEqual(expectedUser);
      expect(mockRepository.save).toHaveBeenCalledWith(
        expect.objectContaining(userData),
      );
    });

    it("should throw ValidationError for invalid email", async () => {
      // Arrange
      const invalidData = { email: "invalid-email", name: "Test User" };

      // Act & Assert
      await expect(service.createUser(invalidData)).rejects.toThrow(
        ValidationError,
      );
      expect(mockRepository.save).not.toHaveBeenCalled();
    });
  });
});

4. テスト命名規則

テスト名は具体的で、何をテストしているかが明確であること:

// ✅ 良い例: 具体的で理解しやすい
it("should return 404 when user does not exist", () => {});
it("should validate email format before saving", () => {});
it("should retry 3 times on network failure", () => {});

// ❌ 悪い例: 曖昧で情報が不足
it("works", () => {});
it("test user", () => {});
it("error case", () => {});

5. テストの独立性

各テストは他のテストに依存しないこと:

// ✅ 良い例: 各テストが独立
describe("UserService", () => {
  let service: UserService;

  beforeEach(() => {
    service = new UserService(); // 各テストで新しいインスタンス
  });

  test("test1", () => {
    /* 他のテストに依存しない */
  });
  test("test2", () => {
    /* 他のテストに依存しない */
  });
});

// ❌ 悪い例: テスト間で状態を共有
let globalUser;
test("create user", () => {
  globalUser = createUser();
});
test("update user", () => {
  updateUser(globalUser);
}); // 前のテストに依存

ルール:

  • beforeEach でインスタンスを再作成
  • テスト間でグローバル変数を共有しない
  • テストの実行順序に依存しない

6. モック・テストデータ管理

モック作成

型安全なモック生成には jest-mock-extended などのライブラリを使用する:

// jest-mock-extended の使用を推奨
import { mock } from "jest-mock-extended";

const mockRepository = mock<IUserRepository>();

データビルダーパターン

テストデータの構築には Builder パターンを使用する:

class UserBuilder {
  private user: Partial<User> = {
    id: "123",
    email: "default@example.com",
    name: "Default User",
  };

  withEmail(email: string): this {
    this.user.email = email;
    return this;
  }

  withName(name: string): this {
    this.user.name = name;
    return this;
  }

  build(): User {
    return this.user as User;
  }
}

// 使用例
const user = new UserBuilder().withEmail("custom@example.com").build();

フィクスチャ

固定のテストデータはフィクスチャファイルで管理する:

// fixtures/users.ts
export const fixtures = {
  validUser: {
    id: "123",
    email: "john@example.com",
    name: "John Doe",
    role: "user",
    createdAt: new Date("2024-01-01"),
  },
  adminUser: {
    id: "456",
    email: "admin@example.com",
    name: "Admin User",
    role: "admin",
    createdAt: new Date("2024-01-01"),
  },
};

7. テスト種別ガイドライン

ユニットテスト

  • 依存関係はすべてモック化
  • 成功パスと失敗パスの両方をテスト
  • describe ブロックで論理的にグループ化
  • 1テストにつき1アサーション(原則)

統合テスト

  • テスト用データベースを使用(本番DBは使わない)
  • beforeAll でアプリ・DB セットアップ
  • afterAll でリソースクリーンアップ
  • beforeEach でデータベース状態をリセット
  • レスポンスとデータベース状態の両方を検証

E2Eテスト

  • Playwright でUI テスト、API クライアントで API テスト
  • クリティカルパス(ユーザー登録、ログイン、主要フロー)を優先
  • バリデーションエラーの表示も検証
  • テストデータは各テストで独立して作成

8. CI/CD 統合

テストは以下の順序で CI パイプラインに組み込む:

  1. Lint チェック
  2. ユニットテスト
  3. 統合テスト
  4. E2E テスト
  5. カバレッジレポートアップロード

テストが失敗した場合、後続のステップは実行しない。

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

プロジェクトガイドラインへの準拠をチェックし、バグ、スタイル違反、コード品質問題を検出する。PRレビュー時に使用。

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

feel-flow/ai-spec-driven-development72026년 10월 18일 업데이트

Enforces project coding standards during code review: naming conventions (PascalCase for classes, camelCase for methods/variables, UPPER_SNAKE_CASE for constants, kebab-case for files), standard file structure, anti-magic-number policy, file size limits (500/800 lines), security patterns, and design patterns. Use when reviewing code, writing new code, or checking adherence to project conventions.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

feel-flow/ai-spec-driven-development72026년 10월 18일 업데이트

機能を保持したまま不要な複雑性を排除し、コードの簡潔性と可読性を向上させる。30行超の関数や3段以上のネスト検出時に使用。

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

feel-flow/ai-spec-driven-development72026년 10월 18일 업데이트

コードコメントの正確性、完全性、長期的な保守性を分析する。JSDoc、コメント、README等のドキュメントが変更された場合に使用。

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

feel-flow/ai-spec-driven-development72026년 10월 18일 업데이트

サイレント失敗を検出し、堅牢なエラーハンドリングを確保する。PRレビューでのエラーハンドリング検査時に使用。

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

feel-flow/ai-spec-driven-development72026년 10월 18일 업데이트

Enforces error handling standards: silent error prohibition, custom error class hierarchy (AppError base with category never-fallback / transient / permanent, cause preservation, ValidationError / UnauthorizedError / UpstreamError etc. — canonical definitions in ERRORS.md), external-boundary normalization (normalizeExternalError), Result pattern (Result.ok/Result.fail), proper try-catch with error type checking, structured error logging with a single Logger contract, fallback prohibition categories (isNeverFallback), and HTTP status code mapping. Use when implementing error handling, reviewing catch blocks, or designing error responses.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

feel-flow/ai-spec-driven-development72026년 10월 18일 업데이트

feel-flow의 스킬 모두 보기

이 스킬의 문제 신고