jpskill.com
🛠️ 開発・MCP コミュニティ

nestjs-testing-skill

NestJS TypeScriptで構築されたバックエンドのテスト(ユニットテスト、結合テスト、E2Eテストなど)を、Jest、TestingModule、Supertestなどのツールを用いて構築、記述、またはリファクタリングするSkill。

📜 元の英語説明(参考)

Use this skill whenever the user wants to set up, write, or refactor tests for a NestJS TypeScript backend, including unit tests, integration tests, and e2e tests with Jest, TestingModule, and Supertest.

🇯🇵 日本人クリエイター向け解説

一言でいうと

NestJS TypeScriptで構築されたバックエンドのテスト(ユニットテスト、結合テスト、E2Eテストなど)を、Jest、TestingModule、Supertestなどのツールを用いて構築、記述、またはリファクタリングするSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o nestjs-testing-skill.zip https://jpskill.com/download/10180.zip && unzip -o nestjs-testing-skill.zip && rm nestjs-testing-skill.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/10180.zip -OutFile "$d\nestjs-testing-skill.zip"; Expand-Archive "$d\nestjs-testing-skill.zip" -DestinationPath $d -Force; ri "$d\nestjs-testing-skill.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して nestjs-testing-skill.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → nestjs-testing-skill フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

NestJS テストスキル (Jest + TestingModule + Supertest)

目的

あなたは、以下を使用してNestJSアプリケーションをテストするための専門的なアシスタントです。

  • 主要なテストランナーとしてのJest
  • NestJS TestingModule ユーティリティ
  • HTTPエンドツーエンド(e2e)テストのためのSupertest

このスキルを使用して、以下を行います。

  • NestJSプロジェクトにおけるテスト設定のセットアップまたは修正
  • サービス、ガード、パイプ、インターセプターのためのユニットテストの作成またはリファクタリング
  • (モックを使用した)コントローラーテストの作成
  • アプリケーションをブートストラップし、実際のHTTPルートを叩くe2eテストの作成
  • テスト構造、命名、およびスクリプトの推奨
  • モックスパイ、および依存関係のオーバーライドの支援

以下の場合は、このスキルを使用しないでください

  • フロントエンドテスト (Next.js, Playwright, RTL) → フロントエンドテストスキルを使用してください
  • 明示的に適合させない限り、非NestJSバックエンド (Hono, raw Express)
  • 負荷/パフォーマンステスト – これは機能的な正確性に焦点を当てています

CLAUDE.md または既存のテスト規約が存在する場合は、それらに従ってください (例: テストフォルダーのレイアウト、命名パターン、または推奨されるマッチャー)。


このスキルを適用するタイミング

ユーザーが次のようなことを言った場合に、このスキルをトリガーします。

  • 「このNestJSプロジェクトのテストをセットアップしてください。」
  • 「このNestJSサービス/コントローラー/ガードのユニットテストを作成してください。」
  • 「これらのルートのe2eテストを追加してください。」
  • 「壊れたNestテストを修正してください。」
  • 「NestJSテストでこの依存関係をモックしてください。」
  • 「このNestアプリでテストを明確に構造化してください。」

以下の場合には避けてください。

  • フロントエンドコードのみがテストされている場合。
  • DBクエリの設計のみが議論されている場合 (TypeORMスキルを使用)。

テストの種類と戦略

このスキルは、テストを3つの主要なカテゴリに分類します。

  1. ユニットテスト

    • サービス、ガード、パイプ、フィルター、および純粋なロジックを分離してテストします。
    • 依存関係はモックされます。
    • Test.createTestingModuleoverrideProvider または単純な手動インスタンス化で使用します。
  2. 統合テスト

    • 複数のNestプロバイダー間の相互作用をテストします (例: サービス + リポジトリ)。
    • (プロジェクトの選択に応じて) 実際のデータベースまたはインメモリデータベースが必要になる場合があります。
  3. エンドツーエンド (e2e) テスト

    • 完全なNestアプリケーション (またはほぼ完全なサブセット) をブートストラップします。
    • HTTPエンドポイントに対して Supertest を使用します。
    • 多くの場合、テストデータベース (またはサンドボックス環境) に対して実行されます。

このスキルは、ユーザーが各問題に対して適切なレベルのテストを選択するのに役立つはずです。


プロジェクトのレイアウトと命名

一般的な規約 (プロジェクトに合わせて調整):

src/
  modules/
    user/
      user.module.ts
      user.service.ts
      user.controller.ts
      __tests__/
        user.service.spec.ts
        user.controller.spec.ts
test/
  app.e2e-spec.ts
  jest-e2e.json
jest.config.ts or jest.config.js

許容されるバリエーション:

  • コードの隣に配置された *.spec.ts または *.test.ts
  • ユニットテスト用の中央集中型 tests/ フォルダー。

このスキルは、ゼロから始める場合を除き、新しいものを課すのではなく、リポジトリ内の既存のパターンに従う必要があります。


Jest の設定

NestJS 用に Jest をセットアップまたは修正する場合、このスキルは以下を保証する必要があります。

  • ルートの Jest 設定が存在する (多くの場合 jest.config.ts)。
  • e2eテストに使用される場合は、e2e 設定 (例: test/jest-e2e.json) が存在する。

Jest の基本設定の例 (簡略化):

// jest.config.ts
import type { Config } from "jest";

const config: Config = {
  preset: "ts-jest",
  testEnvironment: "node",
  moduleFileExtensions: ["js", "json", "ts"],
  rootDir: ".",
  testRegex: ".*\.spec\.ts$",
  transform: {
    "^.+\\.(t|j)s$": "ts-jest",
  },
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
  },
  coverageDirectory: "./coverage",
};

export default config;

E2E 設定の例:

// test/jest-e2e.json
{
  "moduleFileExtensions": ["js", "json", "ts"],
  "rootDir": "../",
  "testEnvironment": "node",
  "testRegex": ".e2e-spec.ts$",
  "transform": {
    "^.+\\.(t|j)s$": "ts-jest"
  }
}

および package.json のスクリプト (必要に応じて調整):

{
  "scripts": {
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  }
}

TestingModule とユニットテスト

サービスまたはコントローラーをテストする場合は、Nest の Test ユーティリティを使用します。

例: サービスユニットテスト

// src/modules/user/__tests__/user.service.spec.ts
import { Test, TestingModule } from "@nestjs/testing";
import { UserService } from "../user.service";
import { getRepositoryToken } from "@nestjs/typeorm";
import { User } from "../entities/user.entity";
import { Repository } from "typeorm";

describe("UserService", () => {
  let service: UserService;
  let repo: jest.Mocked<Repository<User>>;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        UserService,
        {
          provide: getRepositoryToken(User),
          useValue: {
            create: jest.fn(),
            save: jest.fn(),
            findOne: jest.fn(),
            find: jest.fn(),
          },
        },
      ],
    }).compile();

    service = module.get<UserService>(UserService);
    repo = module.get(getRepositoryToken(User));
  });

  it("should create a user", async () => {
    repo.create.mockReturnValue({ id: "1", email: "a@b.com" } as any);
    repo.save.mockResolvedValue({ id: "1", email: "a@b.com" } as any);

    const result = await service.create({ email: "a@b.com", passwordHash: "hash" } as any);

    expect(repo.create).toHaveBeenCalled();
    expect(repo.save).toHaveBeenCalled();
    expect(result.id).toBe("1");
  });
});

このスキルは、以下を推奨する必要があります。

  • TypeORMリポジトリのモックには getRepositoryToken を使用することを推奨します。
  • 役立つ場合は、jest.fn() モックと jest.Mocked<T> 型を使用します。
  • ユニットテストで実際のDBにアクセスすることを避けます。

例: コントローラーユニットテスト


// src/modules/user/__tests__/user.controller.spec.ts
import { Test, TestingModule } from "@nestjs/testing";
import { UserController } from "../user.controller";
import { UserService } from "../user.service";

describe("UserController", () => {
  let controller: UserController;
  let service: jest.Mocked<UserServi

(原文はここで切り詰められています)
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

NestJS Testing Skill (Jest + TestingModule + Supertest)

Purpose

You are a specialized assistant for testing NestJS applications using:

  • Jest as the primary test runner
  • NestJS TestingModule utilities
  • Supertest for HTTP end-to-end (e2e) tests

Use this skill to:

  • Set up or fix testing configuration in a NestJS project
  • Write or refactor unit tests for services, guards, pipes, interceptors
  • Write controller tests (with mocks)
  • Write e2e tests that bootstrap the app and hit real HTTP routes
  • Recommend test structure, naming, and scripts
  • Help with mocking, spies, and dependency overrides

Do not use this skill for:

  • Frontend testing (Next.js, Playwright, RTL) → use frontend testing skills
  • Non-NestJS backends (Hono, raw Express) unless explicitly adapted
  • Load/performance testing – this focuses on functional correctness

If CLAUDE.md or existing test conventions exist, follow them (e.g. test folder layout, naming patterns, or preferred matchers).


When To Apply This Skill

Trigger this skill when the user says things like:

  • “Set up tests for this NestJS project.”
  • “Write unit tests for this NestJS service/controller/guard.”
  • “Add e2e tests for these routes.”
  • “Fix my broken Nest tests.”
  • “Mock this dependency in a NestJS test.”
  • “Structure tests clearly in this Nest app.”

Avoid when:

  • Only frontend code is being tested.
  • Only DB query design is being discussed (use TypeORM skills).

Test Types & Strategy

This skill organizes tests into three main categories:

  1. Unit tests

    • Test services, guards, pipes, filters, and pure logic in isolation.
    • Dependencies are mocked.
    • Use Test.createTestingModule with overrideProvider or simple manual instantiation.
  2. Integration tests

    • Test interactions between a few Nest providers (e.g. service + repository).
    • Might require a real or in-memory database (depending on project choices).
  3. End-to-end (e2e) tests

    • Bootstrap the full Nest application (or a near-full subset).
    • Use Supertest against HTTP endpoints.
    • Often run against a test database (or a sandbox environment).

This skill should help the user choose the right level of test for each problem.


Project Layout & Naming

Common conventions (adjust to project):

src/
  modules/
    user/
      user.module.ts
      user.service.ts
      user.controller.ts
      __tests__/
        user.service.spec.ts
        user.controller.spec.ts
test/
  app.e2e-spec.ts
  jest-e2e.json
jest.config.ts or jest.config.js

Acceptable variations:

  • *.spec.ts or *.test.ts colocated next to code.
  • Centralized tests/ folder for unit tests.

This skill should follow existing patterns in the repo rather than imposing new ones unless starting from scratch.


Jest Configuration

When setting up or fixing Jest for NestJS, this skill should ensure:

  • A root Jest config exists (often jest.config.ts).
  • There is an e2e config (e.g. test/jest-e2e.json) for e2e tests, if used.

Example base Jest config (simplified):

// jest.config.ts
import type { Config } from "jest";

const config: Config = {
  preset: "ts-jest",
  testEnvironment: "node",
  moduleFileExtensions: ["js", "json", "ts"],
  rootDir: ".",
  testRegex: ".*\.spec\.ts$",
  transform: {
    "^.+\\.(t|j)s$": "ts-jest",
  },
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
  },
  coverageDirectory: "./coverage",
};

export default config;

E2E config example:

// test/jest-e2e.json
{
  "moduleFileExtensions": ["js", "json", "ts"],
  "rootDir": "../",
  "testEnvironment": "node",
  "testRegex": ".e2e-spec.ts$",
  "transform": {
    "^.+\.(t|j)s$": "ts-jest"
  }
}

And scripts in package.json (adjust as needed):

{
  "scripts": {
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  }
}

TestingModule & Unit Tests

When testing a service or controller, use Nest’s Test utility:

Example: Service Unit Test

// src/modules/user/__tests__/user.service.spec.ts
import { Test, TestingModule } from "@nestjs/testing";
import { UserService } from "../user.service";
import { getRepositoryToken } from "@nestjs/typeorm";
import { User } from "../entities/user.entity";
import { Repository } from "typeorm";

describe("UserService", () => {
  let service: UserService;
  let repo: jest.Mocked<Repository<User>>;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        UserService,
        {
          provide: getRepositoryToken(User),
          useValue: {
            create: jest.fn(),
            save: jest.fn(),
            findOne: jest.fn(),
            find: jest.fn(),
          },
        },
      ],
    }).compile();

    service = module.get<UserService>(UserService);
    repo = module.get(getRepositoryToken(User));
  });

  it("should create a user", async () => {
    repo.create.mockReturnValue({ id: "1", email: "a@b.com" } as any);
    repo.save.mockResolvedValue({ id: "1", email: "a@b.com" } as any);

    const result = await service.create({ email: "a@b.com", passwordHash: "hash" } as any);

    expect(repo.create).toHaveBeenCalled();
    expect(repo.save).toHaveBeenCalled();
    expect(result.id).toBe("1");
  });
});

This skill should:

  • Encourage using getRepositoryToken for TypeORM repository mocking.
  • Use jest.fn() mocks and jest.Mocked<T> types when helpful.
  • Avoid hitting a real DB in unit tests.

Example: Controller Unit Test

// src/modules/user/__tests__/user.controller.spec.ts
import { Test, TestingModule } from "@nestjs/testing";
import { UserController } from "../user.controller";
import { UserService } from "../user.service";

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

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [UserController],
      providers: [
        {
          provide: UserService,
          useValue: {
            findAll: jest.fn(),
            findOne: jest.fn(),
          },
        },
      ],
    }).compile();

    controller = module.get<UserController>(UserController);
    service = module.get(UserService);
  });

  it("should return all users", async () => {
    service.findAll.mockResolvedValue([{ id: "1" }] as any);
    const result = await controller.findAll();
    expect(result).toEqual([{ id: "1" }]);
    expect(service.findAll).toHaveBeenCalled();
  });
});

This skill should:

  • Encourage thin controllers that are easy to test by mocking services.
  • Use Nest’s DI + TestingModule to instantiate controllers.

E2E Testing with Supertest

For e2e tests, this skill should help create tests that:

  • Bootstrap the real Nest application (or a near-real module subset)
  • Use Supertest to call HTTP endpoints

Example:

// test/app.e2e-spec.ts
import { Test, TestingModule } from "@nestjs/testing";
import { INestApplication } from "@nestjs/common";
import * as request from "supertest";
import { AppModule } from "../src/app.module";

describe("App E2E", () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  afterAll(async () => {
    await app.close();
  });

  it("/health (GET)", async () => {
    const res = await request(app.getHttpServer()).get("/health");
    expect(res.status).toBe(200);
    expect(res.body).toBeDefined();
  });
});

This skill should:

  • Ensure AppModule or the selected root module is imported.
  • Make sure app is shut down after tests to avoid hanging processes.
  • Encourage seeding/cleanup strategies for a test database if used.

Auth & Guards Testing

For routes protected by JWT or other guards, this skill should:

  • Show how to override guards in tests (to focus on controller behavior):
beforeEach(async () => {
  const module: TestingModule = await Test.createTestingModule({
    controllers: [UserController],
    providers: [UserService],
  })
    .overrideGuard(JwtAuthGuard)
    .useValue({ canActivate: () => true })
    .compile();
});
  • Or, for more realistic e2e tests, generate valid JWTs and send them in headers using Supertest.

This interacts with the nestjs-authentication skill, which defines the auth layer.


Test Data & Fixtures

This skill should encourage:

  • Simple, reusable factories for generating test data (can be plain functions or libraries like @faker-js/faker).
  • No reliance on production data sources.
  • Keep fixtures close to tests or in a dedicated test/fixtures folder.

Example:

// test/factories/user.factory.ts
export function makeUser(overrides: Partial<User> = {}): User {
  return {
    id: "user-id",
    email: "test@example.com",
    passwordHash: "hash",
    isActive: true,
    createdAt: new Date(),
    updatedAt: new Date(),
    ...overrides,
  };
}

Debugging Failing Tests

When tests fail, this skill should help:

  • Read Jest error output and identify likely root causes (bad DI, wrong provider token, etc.).
  • Suggest logging/console.log insertion or usage of --runInBand/--detectOpenHandles where helpful.
  • Catch common mistakes:
    • Forgetting to await async methods.
    • Not closing INestApplication in e2e tests.
    • Misconfigured moduleNameMapper or ts-jest paths.

CI Integration

At a high level, this skill can suggest:

  • Running npm test and npm run test:e2e (or pnpm/yarn equivalents) in CI.
  • Ensuring test DB is available and migrated before e2e tests.
  • Using coverage thresholds if desired (coverageThreshold in Jest config).

Detailed CI configuration (GitHub Actions, GitLab CI, etc.) can be offloaded to a dedicated CI/CD skill.


Example Prompts That Should Use This Skill

  • “Write unit tests for this NestJS service.”
  • “Add e2e tests for our auth routes in Nest.”
  • “Mock TypeORM repositories in my Nest tests.”
  • “Fix these failing NestJS Jest tests.”
  • “Set up Jest + ts-jest + Supertest for this Nest project.”

For such tasks, rely on this skill to build a strong testing backbone for your NestJS backend, keeping tests clear, maintainable, and aligned with the project’s architecture.