Skip to main content
rule CX Codex

nestjs-testing — Claude Code rule: unit and E2E tests

nestjs-testing — a rule for NestJS projects: enforces TestingModule for mocked dependencies with Jest, structures E2E tests with Supertest, and prevents real API or database calls during testing.

MIT ★ 372 updated 2026-09-10

Install into Claude Code · Plugin marketplace All methods and platforms ↓
/plugin marketplace add giuseppe-trisciuoglio/developer-kit
/plugin install developer-kit-typescript@developer-kit
Open on GitHub

What nestjs-testing does

The rule defines three testing layers. Unit tests use Test.createTestingModule() to inject mocked providers — services get Jest mock objects injected through the DI container, and afterEach clears all mocks to prevent test pollution. Integration tests mock external services: HTTP clients, repositories, SDKs, with explicit error scenarios like timeouts and 500 responses. E2E tests instantiate the real AppModule, apply global pipes and guards, and verify the complete request–response cycle.

Examples cover authorization guards (401 without token, 200 with valid token), DTO validation, and error handling. Guards and interceptors are tested in isolation using mocked ExecutionContext and CallHandler. Each test follows Arrange-Act-Assert: prepare inputs, execute code, assert outcomes and mock calls.

What it helps with

  • Write unit tests for NestJS services and controllers without leaking to real databases or APIs
  • Mock dependencies (HTTP clients, repositories) in tests using Jest
  • Test authorization guards and DTO validation in E2E flows
  • Isolate E2E tests so they run independently and clean up between runs
  • Verify error paths: timeouts, rate limits, invalid payloads

Example prompts for the agent

  • Write a unit test for UsersService.create() that mocks UserRepository and verifies a conflict exception on duplicate email
  • Add an E2E test for POST /users that validates the DTO and returns 400 for an empty email field
  • Write a test for RolesGuard that confirms a request without the required role returns 403

How to install nestjs-testing

1Plugin marketplace

/plugin marketplace add giuseppe-trisciuoglio/developer-kit
/plugin install developer-kit-typescript@developer-kit

2Manually: put the files in place

.claude/rules/nestjs-testing.md

The paths frontmatter field limits the files

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about nestjs-testing

How do I install nestjs-testing in Claude Code?

Run /plugin marketplace add giuseppe-trisciuoglio/developer-kit, then /plugin install developer-kit-typescript@developer-kit. The rule file will be placed at .claude/rules/nestjs-testing.md.

What does this rule enforce?

It sets testing standards for NestJS: use Test.createTestingModule() for unit tests, mock all external dependencies, write E2E tests with Supertest, and verify authorization flows.

When should I use useValue instead of useClass in a mock provider?

Use useValue with a Jest mock when you need to control return values and verify calls. Use useClass rarely — only if you need a real implementation (typically for utility classes or facades with no side effects).

Source text

nestjs-testing.md · MIT
---
paths:
  - "**/*.spec.ts"
---
# Rule: NestJS Testing

## Context
Enforce testing best practices for NestJS applications: use `@nestjs/testing` for proper DI, mock all external dependencies, and write E2E tests with Supertest.

## Guidelines

### Unit Tests with Testing Module
- **Always** use `Test.createTestingModule()` — never manually instantiate services
- Mock all dependencies using `useValue` with Jest mock objects
- Clear all mocks in `afterEach` to prevent test pollution
- Follow the Arrange-Act-Assert pattern
- Name test variables clearly: `inputX`, `mockX`, `actualX`, `expectedX`

```typescript
// ✅ Proper unit test with Testing Module
describe('UsersService', () => {
  let service: UsersService;
  let repo: jest.Mocked<UserRepository>;

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

    service = module.get<UsersService>(UsersService);
    repo = module.get(UserRepository);
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  describe('create', () => {
    it('should save and return user', async () => {
      const inputDto = { name: 'John', email: '[email protected]' };
      const expectedUser = { id: '1', ...inputDto };
      repo.save.mockResolvedValue(expectedUser);

      const actualUser = await service.create(inputDto);

      expect(actualUser).toEqual(expectedUser);
      expect(repo.save).toHaveBeenCalledWith(inputDto);
    });

    it('should throw on duplicate email', async () => {
      repo.findOne.mockResolvedValue({ id: '1', email: '[email protected]' });

      await expect(
        service.create({ name: 'Test', email: '[email protected]' }),
      ).rejects.toThrow(ConflictException);
    });
  });
});
```

### Mock External Services
- **Never** call real external services (APIs, databases, queues) in unit tests
- Mock HTTP services, repositories, and third-party SDKs
- Test error scenarios: timeouts, rate limiting, 500 errors
- Use `jest.useFakeTimers()` for time-dependent tests
- Create mock factories for complex SDKs

```typescript
// ✅ Mock HTTP service with error scenarios
describe('WeatherService', () => {
  let service: WeatherService;
  let httpService: jest.Mocked<HttpService>;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      providers: [
        WeatherService,
        { provide: HttpService, useValue: { get: jest.fn() } },
      ],
    }).compile();

    service = module.get(WeatherService);
    httpService = module.get(HttpService);
  });

  it('should return weather data', async () => {
    const mockResponse = { data: { temperature: 72 }, status: 200 };
    httpService.get.mockReturnValue(of(mockResponse));

    const result = await service.getWeather('NYC');
    expect(result).toEqual({ temperature: 72 });
  });

  it('should handle API timeout', async () => {
    httpService.get.mockReturnValue(throwError(() => new Error('ETIMEDOUT')));

    await expect(service.getWeather('NYC')).rejects.toThrow('Weather service unavailable');
  });
});

// ✅ Mock repository instead of real database
{ provide: getRepositoryToken(User), useValue: {
    find: jest.fn(),
    findOne: jest.fn(),
    save: jest.fn(),
    delete: jest.fn(),
  },
}
```

### E2E Tests with Supertest
- Use `Test.createTestingModule` with the real `AppModule` for E2E tests
- Apply the same global configuration as production (ValidationPipe, interceptors)
- Test the full request/response cycle: routes, guards, pipes, serialization
- Clean database between tests for isolation
- Test auth flows: 401 without token, 200 with valid token

```typescript
// ✅ E2E test with proper setup
describe('UsersController (e2e)', () => {
  let app: INestApplication;

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

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

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

  it('POST /users — should create a user', () => {
    return request(app.getHttpServer())
      .post('/users')
      .send({ name: 'John', email: '[email protected]' })
      .expect(201)
      .expect((res) => {
        expect(res.body).toHaveProperty('id');
        expect(res.body.name).toBe('John');
      });
  });

  it('POST /users — should return 400 for invalid email', () => {
    return request(app.getHttpServer())
      .post('/users')
      .send({ name: 'John', email: 'invalid-email' })
      .expect(400)
      .expect((res) => {
        expect(res.body.message).toContain('email');
      });
  });

  it('GET /users/:id — should return 404 for non-existent user', () => {
    return request(app.getHttpServer())
      .get('/users/non-existent-id')
      .expect(404);
  });
});

// ✅ E2E test with authentication
describe('Protected Routes (e2e)', () => {
  let app: INestApplication;
  let authToken: string;

  beforeAll(async () => {
    // ... setup
    const loginRes = await request(app.getHttpServer())
      .post('/auth/login')
      .send({ email: '[email protected]', password: 'password' });
    authToken = loginRes.body.accessToken;
  });

  it('should return 401 without token', () => {
    return request(app.getHttpServer()).get('/users/me').expect(401);
  });

  it('should return profile with valid token', () => {
    return request(app.getHttpServer())
      .get('/users/me')
      .set('Authorization', `Bearer ${authToken}`)
      .expect(200);
  });
});
```

### Testing Guards and Interceptors
- Test guards in isolation using mocked `ExecutionContext` and `Reflector`
- Test interceptors with mocked `CallHandler`
- Write controller and service tests separately — each with their own mocks

```typescript
// ✅ Guard unit test
describe('RolesGuard', () => {
  let guard: RolesGuard;
  let reflector: Reflector;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      providers: [RolesGuard, Reflector],
    }).compile();

    guard = module.get(RolesGuard);
    reflector = module.get(Reflector);
  });

  it('should allow when no roles required', () => {
    const context = createMockExecutionContext({ user: { roles: [] } });
    jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(undefined);
    expect(guard.canActivate(context)).toBe(true);
  });
});
```

## Examples

### ✅ Good
```typescript
// Write tests for each controller and service
// Write E2E tests for each API module
// Use Test.createTestingModule for proper DI
// Mock all external dependencies
// Follow Given-When-Then for acceptance tests
// Follow Arrange-Act-Assert for unit tests
```

### ❌ Bad
```typescript
// ❌ Manual instantiation bypassing DI
const repo = new UserRepository();
const service = new UsersService(repo);

// ❌ Calling real external APIs in unit tests
const service = new PaymentService(new StripeClient(realApiKey));

// ❌ No proper setup/teardown in E2E tests
const app = await NestFactory.create(AppModule);
// No cleanup, no config, hits real database
```

© Giuseppe Trisciuoglio · MIT · giuseppe-trisciuoglio/developer-kit

Similar IDE rules

All IDE rules for Testing and QA →

From the same set191

The whole set →
learn learn analyzes a codebase to discover architectural patterns and conventions, then creates rule files in .claude/rules/. Useful when joining a new codebase. CX Codex +1 3,500installs aws-cdk aws-cdk is a Claude Code skill for building and checking AWS infrastructure in TypeScript. It activates for CDK apps, stacks, reusable constructs, and deployment reviews. CX Codex +1 3,500installs bug-fix-brief This skill writes a structured Bug Fix Brief: root cause, repro steps, fix options and a checklist. Handy once a bug is understood but not yet patched. CX Codex +1 3,200installs pr-review-comments pr-review-comments publishes code review findings from a JSON file as inline comments on a GitHub pull request. Useful for attaching review notes directly to modified lines in a diff. CX Codex +1 2,600installs nestjs-database-expert nestjs-database-expert — a subagent for Claude Code dedicated to database operations in NestJS, focusing on Drizzle ORM schemas, migrations, transactions, and query patterns. CX Codex ★ 372repo stars devkit.verify-skill devkit.verify-skill is a Claude Code command that checks a skill against DevKit requirements, its template, and dependencies. Run it before publishing or after edits. CX Codex +1 ★ 372repo stars aws-cloudformation-dynamodb aws-cloudformation-dynamodb — a Claude skill that supplies CloudFormation patterns for DynamoDB tables: keys, indexes, billing modes, TTL and streams. Handy when infrastructure lives in code. CX Codex +1 ★ 372repo stars devkit.java.write-unit-tests devkit.java.write-unit-tests generates JUnit 5 tests with Mockito and AssertJ assertions from a Java class path. Useful for testing Spring Boot services, controllers, and utility classes. CX Codex +1 ★ 372repo stars

Project sponsors

Companies that keep this analytics open