Skip to content

ever-co/ever-works / .agents/skills/nestjs-best-practices

nestjs-best-practices

Verified

NestJS best practices and architecture patterns for building production-ready applications. This skill should be used when writing, reviewing, or refactoring NestJS code to ensure proper patterns for modules, dependency injection, security, and performance.

FileKindSize
AGENTS.mdmarkdown154.2 KB
README.mdmarkdown4.7 KB
SKILL.mdskill md4.8 KB
rules/_sections.mdmarkdown2.1 KB
rules/_template.mdmarkdown633 B
rules/api-use-dto-serialization.mdmarkdown4.2 KB
rules/api-use-interceptors.mdmarkdown5.4 KB
rules/api-use-pipes.mdmarkdown5.3 KB
rules/api-versioning.mdmarkdown4.7 KB
rules/arch-avoid-circular-deps.mdmarkdown1.9 KB
rules/arch-feature-modules.mdmarkdown2.3 KB
rules/arch-module-sharing.mdmarkdown3.7 KB
rules/arch-single-responsibility.mdmarkdown2.8 KB
rules/arch-use-events.mdmarkdown2.9 KB
rules/arch-use-repository-pattern.mdmarkdown2.7 KB
rules/db-avoid-n-plus-one.mdmarkdown3.8 KB
rules/db-use-migrations.mdmarkdown3.7 KB
rules/db-use-transactions.mdmarkdown3.6 KB
rules/devops-graceful-shutdown.mdmarkdown5.5 KB
rules/devops-use-config-module.mdmarkdown4.2 KB
rules/devops-use-logging.mdmarkdown5.1 KB
rules/di-avoid-service-locator.mdmarkdown2.8 KB
rules/di-interface-segregation.mdmarkdown5.0 KB
rules/di-liskov-substitution.mdmarkdown6.8 KB
rules/di-prefer-constructor-injection.mdmarkdown2.2 KB
rules/di-scope-awareness.mdmarkdown2.5 KB
rules/di-use-interfaces-tokens.mdmarkdown2.5 KB
rules/error-handle-async-errors.mdmarkdown3.4 KB
rules/error-throw-http-exceptions.mdmarkdown3.0 KB
rules/error-use-exception-filters.mdmarkdown3.4 KB
rules/micro-use-health-checks.mdmarkdown6.1 KB
rules/micro-use-patterns.mdmarkdown5.0 KB
rules/micro-use-queues.mdmarkdown5.7 KB
rules/perf-async-hooks.mdmarkdown2.8 KB
rules/perf-lazy-loading.mdmarkdown3.6 KB
rules/perf-optimize-database.mdmarkdown3.0 KB
rules/perf-use-caching.mdmarkdown3.3 KB
rules/security-auth-jwt.mdmarkdown3.8 KB
rules/security-rate-limiting.mdmarkdown3.1 KB
rules/security-sanitize-output.mdmarkdown3.7 KB
rules/security-use-guards.mdmarkdown3.4 KB
rules/security-validate-all-input.mdmarkdown3.2 KB
rules/test-e2e-supertest.mdmarkdown4.4 KB
rules/test-mock-external-services.mdmarkdown4.2 KB
rules/test-use-testing-module.mdmarkdown4.1 KB
scripts/build-agents.tsscript8.1 KB
scripts/build.shscript369 B
scripts/package-lock.jsonmanifest7.7 KB
scripts/package.jsonmanifest410 B

rules/test-mock-external-services.md

View on GitHub
---
title: Mock External Services in Tests
impact: HIGH
impactDescription: Ensures fast, reliable, deterministic tests
tags: testing, mocking, external-services, jest
---

## Mock External Services in Tests

Never call real external services (APIs, databases, message queues) in unit tests. Mock them to ensure tests are fast, deterministic, and don't incur costs. Use realistic mock data and test edge cases like timeouts and errors.

**Incorrect (calling real APIs and databases):**

```typescript
// Call real APIs in tests
describe('PaymentService', () => {
	it('should process payment', async () => {
		const service = new PaymentService(new StripeClient(realApiKey));
		// Hits real Stripe API!
		const result = await service.charge('tok_visa', 1000);
		// Slow, costs money, flaky
	});
});

// Use real database
describe('UsersService', () => {
	beforeEach(async () => {
		await connection.query('DELETE FROM users'); // Modifies real DB
	});

	it('should create user', async () => {
		const user = await service.create({ email: 'test@test.com' });
		// Side effects on shared database
	});
});

// Incomplete mocks
const mockHttpService = {
	get: jest.fn().mockResolvedValue({ data: {} })
	// Missing error scenarios, missing other methods
};
```

**Correct (mock all external dependencies):**

```typescript
// Mock HTTP service properly
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(),
						post: jest.fn()
					}
				}
			]
		}).compile();

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

	it('should return weather data', async () => {
		const mockResponse = {
			data: { temperature: 72, humidity: 45 },
			status: 200,
			statusText: 'OK',
			headers: {},
			config: {}
		};

		httpService.get.mockReturnValue(of(mockResponse));

		const result = await service.getWeather('NYC');

		expect(result).toEqual({ temperature: 72, humidity: 45 });
	});

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

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

	it('should handle rate limiting', async () => {
		httpService.get.mockReturnValue(
			throwError(() => ({
				response: { status: 429, data: { message: 'Rate limited' } }
			}))
		);

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

// Mock repository instead of database
describe('UsersService', () => {
	let service: UsersService;
	let repo: jest.Mocked<Repository<User>>;

	beforeEach(async () => {
		const mockRepo = {
			find: jest.fn(),
			findOne: jest.fn(),
			save: jest.fn(),
			delete: jest.fn(),
			createQueryBuilder: jest.fn()
		};

		const module = await Test.createTestingModule({
			providers: [UsersService, { provide: getRepositoryToken(User), useValue: mockRepo }]
		}).compile();

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

	it('should find user by id', async () => {
		const mockUser = { id: '1', name: 'John', email: 'john@test.com' };
		repo.findOne.mockResolvedValue(mockUser);

		const result = await service.findById('1');

		expect(result).toEqual(mockUser);
		expect(repo.findOne).toHaveBeenCalledWith({ where: { id: '1' } });
	});
});

// Create mock factory for complex SDKs
function createMockStripe(): jest.Mocked<Stripe> {
	return {
		paymentIntents: {
			create: jest.fn(),
			retrieve: jest.fn(),
			confirm: jest.fn(),
			cancel: jest.fn()
		},
		customers: {
			create: jest.fn(),
			retrieve: jest.fn()
		}
	} as any;
}

// Mock time for time-dependent tests
describe('TokenService', () => {
	beforeEach(() => {
		jest.useFakeTimers();
		jest.setSystemTime(new Date('2024-01-15'));
	});

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

	it('should expire token after 1 hour', async () => {
		const token = await service.createToken();

		// Fast-forward time
		jest.advanceTimersByTime(61 * 60 * 1000);

		expect(await service.isValid(token)).toBe(false);
	});
});
```

Reference: [Jest Mocking](https://jestjs.io/docs/mock-functions)
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall