nestjs-testing — правило для Claude Code: модульные и E2E тесты
Правило nestjs-testing для NestJS-проектов: тестирует сервисы через TestingModule, мокирует зависимости Jest и пишет E2E-тесты с Supertest. Нужно, чтобы тесты не вызывали реальные API и БД.
MIT ★ 372 обновлён 2026-09-10
/plugin marketplace add giuseppe-trisciuoglio/developer-kit
/plugin install developer-kit-typescript@developer-kitЧто делает nestjs-testing
Правило задаёт три уровня тестирования. На уровне модуля используется Test.createTestingModule() с мокированными провайдерами — зависимости заменяются Jest-объектами, afterEach очищает все моки. На уровне интеграции мокируются внешние сервисы: HTTP-клиенты, репозитории, SDK. Ошибки (таймауты, 500-е ответы) тестируются явно. E2E-тесты собирают настоящий AppModule, применяют глобальные пайпы и гварды, проверяют весь путь запроса — от маршрута до ответа.
Правило включает примеры охраны авторизации (401 без токена, 200 с валидным), валидации DTO и обработки ошибок. Гварды и интерсепторы тестируются отдельно с мокированными ExecutionContext и CallHandler. Каждый тест следует паттерну Arrange-Act-Assert: входные данные, вызов метода, проверка результата и вызовов.
Какие задачи решает
- Писать unit-тесты для NestJS-сервисов и контроллеров без утечек в реальные БД и API
- Мокировать зависимости (HTTP-клиенты, репозитории) в тестах через Jest
- Тестировать охрану авторизации и валидацию DTO в E2E
- Структурировать E2E-тесты так, чтобы они изолировались между прогонами
- Проверять сценарии ошибок: таймауты, rate-limiting, невалидные данные
Примеры запросов агенту
- Напиши unit-тест для
UsersService.create(), который мокируетUserRepositoryи проверяет, что при дублирующемся email выбросится исключение - Добавь E2E-тест для
POST /users, который валидирует DTO и возвращает 400 при пустом email - Напиши тест для гварда
RolesGuard, который проверяет, что запрос без нужной роли вернёт 403
Как установить nestjs-testing
1Через маркетплейс плагинов
/plugin marketplace add giuseppe-trisciuoglio/developer-kit/plugin install developer-kit-typescript@developer-kit2Вручную: положить файлы
.claude/rules/nestjs-testing.mdПоле paths во frontmatter ограничивает файлы
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.cursor/rules/nestjs-testing.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.github/instructions/nestjs-testing.instructions.mdПоле applyTo задаёт, к каким файлам применять
Вручную: положить файлы
.devin/rules/nestjs-testing.mdВручную: положить файлы
.clinerules/nestjs-testing.mdПо шагам, с командами для каждой платформы: AGENTS.md и CLAUDE.md: что это, кто читает и какой выбрать
Вопросы о nestjs-testing
Как установить nestjs-testing в Claude Code?
Выполни /plugin marketplace add giuseppe-trisciuoglio/developer-kit, затем /plugin install developer-kit-typescript@developer-kit. Файл правила будет в .claude/rules/nestjs-testing.md.
Что делает это правило?
Задаёт стандарты тестирования для NestJS: использование Test.createTestingModule() для unit-тестов, мокирование всех внешних зависимостей, написание E2E-тестов с Supertest и проверку охраны авторизации.
Когда в тесте используется useValue, а когда useClass?
Используй useValue с Jest-моком, когда нужно контролировать возвращаемые значения и проверять вызовы. Используй useClass редко — только если тебе нужна настоящая реализация (обычно для фасадов или утилит без побочных эффектов).
Исходный текст
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