本文へ移動
cccskills
無料GitHub で公開

nest-testing

NestJS testing patterns: Test.createTestingModule for unit/integration, mocking providers, e2e tests with INestApplication + supertest, ORM mocking (TypeORM/Prisma/Mongoose), test fixtures. Use this skill to: - Write unit tests for services with mocked dependencies. - Write integration tests with real DI but mocked external services. - Write e2e tests for HTTP endpoints via supertest. - Mock repositories/Prisma client correctly. - Cover services and controllers to ≥80%. Do NOT use this skill for: - Test framework setup (Jest/Vitest config — usually already in place). - Frontend tests. - Load testing (out of QA scope).

インストール方法を見る

含まれるファイル(1)

  • SKILL.md9.2 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

NestJS Testing

NestJS has a first-class testing module. The pattern: build a synthetic IoC container with the providers you want, override what you need, and exercise the system.

Test framework

Default in Nest CLI is Jest. If the project uses Vitest, the patterns translate 1:1 — the imports change (@nestjs/testing works with both).

Test scripts in package.json:

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

E2E tests live in test/ (or apps/<app>/test/ in monorepo) and use a separate Jest config that picks up *.e2e-spec.ts.

Unit test — service with mocked deps

// src/users/users.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UsersService } from './users.service';
import { User } from './entities/user.entity';

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

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

    service = module.get(UsersService);
    repo = module.get(getRepositoryToken(User));
  });

  it('finds a user by email', async () => {
    const user = { id: '1', email: 'a@b.c' } as User;
    repo.findOne.mockResolvedValue(user);
    expect(await service.findByEmail('a@b.c')).toBe(user);
    expect(repo.findOne).toHaveBeenCalledWith({ where: { email: 'a@b.c' } });
  });

  it('returns null when not found', async () => {
    repo.findOne.mockResolvedValue(null);
    expect(await service.findByEmail('missing@b.c')).toBeNull();
  });
});

Key points:

  • Use getRepositoryToken(Entity) as the provider token — TypeORM's @InjectRepository resolves to this.
  • Type the mock as jest.Mocked<Repository<User>> for autocomplete and type safety on mockResolvedValue / mockRejectedValue.

Mocking Prisma

import { mockDeep, DeepMockProxy } from 'jest-mock-extended';
import { PrismaClient } from '@prisma/client';

let prisma: DeepMockProxy<PrismaClient>;

beforeEach(async () => {
  prisma = mockDeep<PrismaClient>();
  const module = await Test.createTestingModule({
    providers: [
      UsersService,
      { provide: PrismaService, useValue: prisma },
    ],
  }).compile();
  service = module.get(UsersService);
});

it('creates a user', async () => {
  const created = { id: '1', email: 'a@b.c' };
  prisma.user.create.mockResolvedValue(created as any);
  const result = await service.create({ email: 'a@b.c', password: 'secret' });
  expect(result).toEqual(created);
});

jest-mock-extended (pnpm add -D jest-mock-extended) provides typed deep mocks — Prisma's nested API (prisma.user.create, prisma.user.findMany) gets full type info.

Mocking Mongoose

import { getModelToken } from '@nestjs/mongoose';

const userModelMock = {
  findOne: jest.fn().mockReturnValue({ exec: jest.fn() }),
  create: jest.fn(),
  // ...
};

beforeEach(async () => {
  const module = await Test.createTestingModule({
    providers: [
      UsersService,
      { provide: getModelToken(User.name), useValue: userModelMock },
    ],
  }).compile();
});

Mongoose's chained API (.findOne().exec()) makes mocks fiddly — return { exec: jest.fn() } from each query method.

Integration test — real container, mocked external services

For controllers with services, often you want real DI through the controller-service-repository chain but mock the database:

const module = await Test.createTestingModule({
  controllers: [UsersController],
  providers: [
    UsersService,
    { provide: getRepositoryToken(User), useValue: repoMock },
    { provide: MailerService, useValue: { send: jest.fn().mockResolvedValue(undefined) } },
  ],
})
  .overrideGuard(JwtAuthGuard)
  .useValue({ canActivate: () => true })
  .compile();

.overrideGuard(...).useValue(...) is the cleanest way to bypass auth in tests.

E2E test

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

describe('UsersController (e2e)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    })
      .overrideProvider(MailerService).useValue({ send: jest.fn() })
      .compile();

    app = module.createNestApplication();
    app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }));
    await app.init();
  });

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

  it('POST /users → 201', async () => {
    const res = await request(app.getHttpServer())
      .post('/users')
      .send({ email: 'new@user.com', password: 'longenough' })
      .expect(201);
    expect(res.body).toMatchObject({ email: 'new@user.com' });
    expect(res.body).not.toHaveProperty('passwordHash');
  });

  it('POST /users with extra field → 400', async () => {
    await request(app.getHttpServer())
      .post('/users')
      .send({ email: 'a@b.c', password: 'longenough', isAdmin: true })
      .expect(400);                         // forbidNonWhitelisted catches this
  });
});

Use app.getHttpServer() (not app.listen()) — supertest binds to a random port itself.

For database, prefer:

  • A test container (Postgres/Mongo via Testcontainers) per suite.
  • Or a separate test database with migrations applied in beforeAll.
  • Or in-memory (sqlite-memory for TypeORM, mongo-memory-server) for speed — caveat: subtle differences from real DB.

E2E test database setup pattern

beforeAll(async () => {
  const module = await Test.createTestingModule({
    imports: [AppModule],
  })
    .overrideProvider(getDataSourceToken())
    .useFactory({
      factory: async () => {
        const ds = new DataSource({
          type: 'sqlite',
          database: ':memory:',
          entities: [User, Order],
          synchronize: true,                 // OK in tests
        });
        await ds.initialize();
        return ds;
      },
    })
    .compile();
  // ...
});

Test fixtures

For repeated entities, factory functions:

// test/factories/user.factory.ts
import { faker } from '@faker-js/faker';
import { User } from '../../src/users/entities/user.entity';

export const userFactory = (overrides: Partial<User> = {}): User => ({
  id: faker.string.uuid(),
  email: faker.internet.email(),
  passwordHash: '$argon2id$...',
  metadata: {},
  createdAt: new Date(),
  updatedAt: new Date(),
  ...overrides,
} as User);

Use userFactory({ email: 'specific@x.com' }) in tests to override what matters and get reasonable defaults for the rest.

Coverage discipline

Target ≥80% for services and controllers. These hold business logic.

Don't measure coverage on:

  • Modules (*.module.ts) — pure configuration.
  • Decorator definitions — DSL, not logic.
  • DTOs/entities — schemas, not logic.
  • main.ts — bootstrap.

Configure Jest to exclude:

// package.json
{
  "jest": {
    "collectCoverageFrom": [
      "src/**/*.{ts,js}",
      "!src/**/*.module.ts",
      "!src/**/*.dto.ts",
      "!src/**/*.entity.ts",
      "!src/main.ts"
    ]
  }
}

Iteration cap (from QA agent)

The qa-engineer agent has a hard 3-attempt cap on fixing failing tests. If a test is fundamentally fragile after 3 attempts, mark it it.skip(...) with a comment explaining why and report in the QA summary. Don't iterate past the cap.

Anti-patterns

  • ❌ Sharing mock state between tests without beforeEach reset.
  • ❌ Real database calls in unit tests (slow, flaky).
  • ❌ E2E tests against localhost:3000 — use app.getHttpServer() so each test creates its own port.
  • ❌ Asserting on body.passwordHash not being there as the only protection — also test that the endpoint excludes it via DTO/serializer.
  • ❌ expect(spy).toHaveBeenCalled() without .toHaveBeenCalledWith(...) — half a test.
  • ❌ Long e2e tests that exercise dozens of routes — split per resource.
  • ❌ Mocking the SUT (test the real thing; mock its deps).

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

Angular 18-21 project structure, standalone components vs NgModule, control flow (@if/@for/@switch + *ngIf/*ngFor legacy), decorators, dependency injection (inject() function), lifecycle hooks, pipes, Angular Universal SSR pointer. Use this skill to: - Detect project style (standalone vs NgModule) and apply matching patterns. - Pick correct decorators and DI approach. - Use modern control flow (@if/@for/@switch) in Angular 17+ projects. - Apply `inject()` function over constructor injection where appropriate. - Wire bootstrap correctly (bootstrapApplication for standalone, AppModule for legacy). Do NOT use this skill for: - State management (see angular-state-and-rx). - Routing (see angular-routing). - Forms (see angular-forms). - Testing (see angular-testing).

日本語の概要は準備中です。原文の説明を表示しています。

AratKruglik/claude-sdlc362026年9月21日 更新

Angular forms: Reactive Forms (preferred — typed FormGroup/FormControl since Angular 14, FormBuilder, custom + async validators, FormArray, multi-step) and Template-driven (`[(ngModel)]` + FormsModule). Validation strategies, server error mapping, accessibility. Use this skill to: - Build Reactive Forms with typed FormGroup/FormControl. - Use FormBuilder для concise syntax. - Implement custom synchronous and async validators. - Wire FormArray for dynamic field lists. - Map server errors back to form fields. - Pick Reactive vs Template-driven (prefer Reactive). Do NOT use this skill for: - General conventions (see angular-conventions). - State management beyond forms (see angular-state-and-rx). - Routing (see angular-routing). - Testing forms (see angular-testing).

日本語の概要は準備中です。原文の説明を表示しています。

AratKruglik/claude-sdlc362026年9月21日 更新

Angular Router (built-in `@angular/router`) — route configuration for standalone and NgModule projects, functional guards (Angular 14.1+), lazy loading, route resolvers, typed params via signals/observables, programmatic navigation, route data and meta. Use this skill to: - Configure routes (standalone-style or NgModule-style). - Use functional guards (canActivate as function, preferred over class-based in 17+). - Lazy-load components or feature modules. - Implement auth guards via route meta + functional guards. - Read params/queries via `inject(ActivatedRoute)` + signals or RxJS. Do NOT use this skill for: - General conventions (see angular-conventions). - State management (see angular-state-and-rx). - Forms (see angular-forms). - Testing routes (see angular-testing).

日本語の概要は準備中です。原文の説明を表示しています。

AratKruglik/claude-sdlc362026年9月21日 更新

State management for Angular 18-21: signals (signal/computed/effect), services-as-state, NgRx Store + Effects + Selectors, NgRx Component Store, NgRx Signals (newer signal-based store). RxJS essentials — operators, async pipe, takeUntilDestroyed, signal/observable interop. Use this skill to: - Pick the right state tool (signals / services / NgRx variant / vue-query equivalent). - Use signals correctly (signal/computed/effect — when each). - Build a Pinia-style service-as-state singleton. - Set up NgRx Store + Effects + Selectors. - Use RxJS without leaking subscriptions (async pipe, takeUntilDestroyed, Subject patterns). - Bridge signals ↔ observables via toSignal / toObservable. Do NOT use this skill for: - General Angular conventions (see angular-conventions). - Routing state (see angular-routing). - Form state (see angular-forms). - Testing state (see angular-testing).

日本語の概要は準備中です。原文の説明を表示しています。

AratKruglik/claude-sdlc362026年9月21日 更新

Testing Angular 18-21: TestBed, component harnesses (@angular/cdk/testing), Karma+Jasmine (default historical) vs Jest (jest-preset-angular, modern), Angular Testing Library (RTL-style). HttpClient mocking via HttpTestingController. NgRx Effects testing. Cypress / Playwright e2e. Use this skill to: - Detect runner (Karma+Jasmine vs Jest) and configure correctly. - Write component tests with TestBed. - Use component harnesses for Material / custom UI components. - Mock HttpClient via provideHttpClientTesting + HttpTestingController. - Test signal-based inputs with componentRef.setInput(). - Test NgRx Effects with provideMockActions. Do NOT use this skill for: - General Angular conventions (see angular-conventions). - Routing patterns broadly (see angular-routing — covers testing routes briefly). - Form patterns broadly (see angular-forms).

日本語の概要は準備中です。原文の説明を表示しています。

AratKruglik/claude-sdlc362026年9月21日 更新

Shared conventions for every SDLC development-phase architect agent: hard rules, code quality bar, workflow steps (superpowers invocation, spec reading, codebase exploration, verification), and the report/compact-summary contract. Architects load this skill first, then apply their stack-specific instructions on top.

日本語の概要は準備中です。原文の説明を表示しています。

AratKruglik/claude-sdlc362026年9月21日 更新

AratKruglik のスキルをすべて見る

このスキルの問題を報告する