проектdocs/Agents/rules/testing-nestjs.md
testing-nestjs.md
Обновлён 1 апр. 2026 г., 12:41 · 0 комментариев
title: NestJS Testing Patterns impact: HIGH impactDescription: Ensures reliable backend through proper test structure tags: testing, nestjs, jest, mocking
Паспорт документа
- Статус документа: living standard
- Актуально на: 28 марта 2026 года
- Владелец: backend/platform-команда
- Пересмотр: при изменении инженерной практики, CI/CD, архитектурных правил или локального workflow
- Область применения: внутренние rule/reference-card документы для инженерной команды
- Связанные документы:
NestJS Testing Patterns
Impact: HIGH
Unit Tests (Services)
Mock all dependencies. Test business logic in isolation.
describe('CatalogService', () => {
let service: CatalogService;
let repo: jest.Mocked<CatalogRepository>;
let cache: jest.Mocked<CacheService>;
beforeEach(async () => {
const module = await Test.createTestingModule({
providers: [
CatalogService,
{ provide: CatalogRepository, useValue: createMock<CatalogRepository>() },
{ provide: CacheService, useValue: createMock<CacheService>() },
],
}).compile();
service = module.get(CatalogService);
repo = module.get(CatalogRepository);
cache = module.get(CacheService);
});
it('uses cache for catalog queries', async () => {
const items = [{ id: '1', title: 'Course' }];
cache.getOrSet.mockImplementation((_key, _ttl, factory) => factory());
repo.findPublished.mockResolvedValue(items);
const result = await service.getPublishedItems({});
expect(cache.getOrSet).toHaveBeenCalled();
expect(result).toEqual(items);
});
});
Integration Tests (Controllers)
Use Supertest to test HTTP endpoints with real NestJS app.
describe('CatalogController (e2e)', () => {
let app: INestApplication;
beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [CatalogModule, PrismaModule],
}).compile();
app = module.createNestApplication();
await app.init();
});
it('GET /catalog returns published items', () => {
return request(app.getHttpServer())
.get('/catalog')
.expect(200)
.expect(res => {
expect(Array.isArray(res.body.items)).toBe(true);
});
});
afterAll(() => app.close());
});
Rules
- Unit test services with mocked dependencies
- Integration test controllers with real HTTP requests
- Never test private methods — test through the public API
- Use factories for test data (
createMockItem(),createMockSeller())