Skip to content

HigorAlves/orc / codex/orc/content/skills/nestjs-best-practices

nestjs-best-practices

Verified

NestJS best practices and architecture patterns for production apps

FileKindSize
.github/workflows/branch-protection.ymlconfig760 B
.github/workflows/deploy.ymlconfig1.2 KB
.gitignoreother237 B
AGENTS.mdmarkdown159.2 KB
README.mdmarkdown4.4 KB
SKILL.mdskill md4.5 KB
rules/_sections.mdmarkdown2.1 KB
rules/_template.mdmarkdown631 B
rules/api-use-dto-serialization.mdmarkdown4.3 KB
rules/api-use-interceptors.mdmarkdown5.4 KB
rules/api-use-pipes.mdmarkdown5.3 KB
rules/api-versioning.mdmarkdown4.9 KB
rules/arch-avoid-circular-deps.mdmarkdown2.0 KB
rules/arch-feature-modules.mdmarkdown2.3 KB
rules/arch-module-sharing.mdmarkdown3.8 KB
rules/arch-single-responsibility.mdmarkdown2.9 KB
rules/arch-use-events.mdmarkdown3.0 KB
rules/arch-use-repository-pattern.mdmarkdown2.8 KB
rules/db-avoid-n-plus-one.mdmarkdown3.8 KB
rules/db-use-migrations.mdmarkdown3.7 KB
rules/db-use-transactions.mdmarkdown3.9 KB
rules/devops-graceful-shutdown.mdmarkdown5.8 KB
rules/devops-use-config-module.mdmarkdown4.3 KB
rules/devops-use-logging.mdmarkdown5.6 KB
rules/di-avoid-service-locator.mdmarkdown2.9 KB
rules/di-interface-segregation.mdmarkdown5.1 KB
rules/di-liskov-substitution.mdmarkdown7.1 KB
rules/di-prefer-constructor-injection.mdmarkdown2.3 KB
rules/di-scope-awareness.mdmarkdown2.6 KB
rules/di-use-interfaces-tokens.mdmarkdown2.5 KB
rules/error-handle-async-errors.mdmarkdown3.4 KB
rules/error-throw-http-exceptions.mdmarkdown3.1 KB
rules/error-use-exception-filters.mdmarkdown3.6 KB
rules/micro-use-health-checks.mdmarkdown5.8 KB
rules/micro-use-patterns.mdmarkdown5.0 KB
rules/micro-use-queues.mdmarkdown6.1 KB
rules/perf-async-hooks.mdmarkdown2.8 KB
rules/perf-lazy-loading.mdmarkdown3.7 KB
rules/perf-optimize-database.mdmarkdown3.2 KB
rules/perf-use-caching.mdmarkdown3.4 KB
rules/security-auth-jwt.mdmarkdown4.0 KB
rules/security-rate-limiting.mdmarkdown3.2 KB
rules/security-sanitize-output.mdmarkdown3.7 KB
rules/security-use-guards.mdmarkdown3.6 KB
rules/security-validate-all-input.mdmarkdown3.3 KB
rules/test-e2e-supertest.mdmarkdown4.7 KB
rules/test-mock-external-services.mdmarkdown4.5 KB
rules/test-use-testing-module.mdmarkdown4.3 KB
scripts/build-agents.tsscript8.5 KB
scripts/build.shexecutablescript369 B
scripts/package-lock.jsonmanifest8.5 KB
scripts/package.jsonmanifest428 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)
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall