Skip to content

NestJS Testing

Nest ships with Jest-friendly testing utilities. This lesson maps the testing landscape: unit tests with TestingModule and e2e tests with a running Nest app.

Nest Testing Philosophy

Unit tests instantiate providers with mocked dependencies via Test.createTestingModule. E2E tests boot an application (often with overrides) and hit HTTP endpoints with Supertest. Prefer many fast unit tests and fewer broader e2e tests.

const moduleRef = await Test.createTestingModule({
  providers: [CatsService, { provide: CatsRepository, useValue: mockRepo }],
}).compile();

const service = moduleRef.get(CatsService);

useValue mocks replace real repositories so unit tests stay in-memory and fast.

Test Types in Nest Projects

*.spec.ts     -> unit tests next to source
test/*.e2e-spec.ts -> end-to-end HTTP tests
  • Default Nest CLI projects already include Jest configuration.
  • Override providers in TestingModule instead of patching imports awkwardly.
  • Test behavior of public APIs (service methods, HTTP contracts), not private internals.
  • Reset modules between tests when request-scoped providers or mutable mocks are involved.

Testing Overview Cheatsheet

What each Nest test style covers.

Style Focus
Unit Single provider with mocked deps
Integration Few real modules collaborating
E2E Full HTTP request through Nest pipeline
Contract API shape stability for clients

DI Makes Testing Easier

Because Nest injects dependencies, swapping a real AuthService for a fake is a module configuration change—no invasive monkey-patching required.

Coverage Goals

Chase meaningful assertions over % numbers. Guard auth boundaries, validation failures, and critical business rules first.

Common Mistakes

  • Writing e2e tests for every tiny branch instead of unit testing them.
  • Sharing mutable mock state across tests without resets.
  • Bootstrapping the full AppModule for simple service tests.
  • Asserting implementation details rather than outputs and side effects.

Key Takeaways

  • Nest testing centers on TestingModule and provider overrides.
  • Unit and e2e tests play complementary roles.
  • DI enables clean mocks via useValue/useClass.
  • Prefer fast unit tests for logic; e2e for wiring and HTTP contracts.

Pro Tip

Create shared test helpers for building TestingModules with common mocks (ConfigService, Prisma) so each spec stays focused on the scenario.