Skip to content

TestingModuleBuilder

reference
3 min readUpdated

Kind: Class

Source: packages/testing/testing-module.builder.ts

Part of: Testing

TestingModuleBuilder configures and compiles a NestJS testing module before it is used in tests. It supports overriding providers, modules, guards, pipes, filters, and interceptors, configuring a custom logger, and supplying a mocker for unresolved dependencies. Calling compile() produces a TestingModule that can resolve and exercise application components in isolation.

Methods

MethodSignatureReturns
setLoggersetLogger(testingLogger: LoggerService)void
overridePipeoverridePipe(typeOrToken: T)OverrideBy
useMockeruseMocker(mocker: MockFactory)TestingModuleBuilder
overrideFilteroverrideFilter(typeOrToken: T)OverrideBy
overrideGuardoverrideGuard(typeOrToken: T)OverrideBy
overrideInterceptoroverrideInterceptor(typeOrToken: T)OverrideBy
overrideProvideroverrideProvider(typeOrToken: T)OverrideBy
overrideModuleoverrideModule(moduleToOverride: ModuleDefinition)OverrideModule
compile`compile(options: Pick<NestApplicationContextOptions, 'snapshot''preview'>)`

Diagram

mermaid
graph LR
  A[Test.createTestingModule metadata] --> B[TestingModuleBuilder]
  B --> C[Configure logger or mocker]
  B --> D[Override providers/modules]
  B --> E[Override guards/pipes/filters/interceptors]
  C --> F[compile()]
  D --> F
  E --> F
  F --> G[TestingModule]
  G --> H[module.get()]
  G --> I[Application or unit tests]

Usage

ts
import { Test } from '@nestjs/testing';
import { UsersService } from './users.service';
import { UsersRepository } from './users.repository';

describe('UsersService', () => {
  let usersService: UsersService;

  beforeEach(async () => {
    const moduleRef = await Test.createTestingModule({
      providers: [UsersService, UsersRepository],
    })
      .overrideProvider(UsersRepository)
      .useValue({
        findById: jest.fn().mockResolvedValue({
          id: 'user-1',
          email: 'user@example.com',
        }),
      })
      .useMocker((token) => {
        if (token === 'EMAIL_CLIENT') {
          return { send: jest.fn() };
        }
      })
      .compile();

    usersService = moduleRef.get(UsersService);
  });

  it('returns a user', async () => {
    await expect(usersService.findById('user-1')).resolves.toEqual({
      id: 'user-1',
      email: 'user@example.com',
    });
  });
});

AI Coding Instructions

  • Create the builder through Test.createTestingModule() and call compile() only after all module configuration and overrides are complete.
  • Use overrideProvider(), overrideGuard(), overridePipe(), overrideFilter(), or overrideInterceptor() to replace production dependencies with deterministic test doubles.
  • Use useMocker() for automatic fallback mocks, but explicitly override dependencies whose behavior is important to the test scenario.
  • Keep overrides scoped to the testing module; do not modify production module metadata or global application configuration for test-specific behavior.
  • Retrieve compiled dependencies from TestingModule with moduleRef.get() and reset Jest mocks between tests when mock state can leak.

How it works

TestingModuleBuilder is the mutable builder returned by Test.createTestingModule(metadata, options). It accepts module metadata and optional moduleIdGeneratorAlgorithm configuration, creates a NestContainer, and turns the metadata into a dynamically decorated RootTestModule. packages/testing/test.ts:11-16 packages/testing/testing-module.builder.ts:29-32 packages/testing/testing-module.builder.ts:49-56 packages/testing/testing-module.builder.ts:195-199

Was this page helpful?

Download as PDF
TestingModuleBuilder — NestJS head-to-head