skip to content

Test Modules & E2E

Test.createTestingModule builds a module graph you can override provider by provider, and createNestApplication serves it to e2e requests. Interviewers ask how to replace a global guard in a test.

on this pageshow

explore

questions

5

In NestJS, how do you unit-test an OrdersService with Test.createTestingModule() and a fake repository?

level: juniorimportance: must knowfreq 62%

answer

  1. same shape as @Module metadata
  2. a builder, then an awaited step
  3. custom provider stands in
  4. read the instance back out

basics

~10 s

Test.createTestingModule() takes the same metadata as @Module() and returns a builder; awaiting compile() wires a real Nest container. Register OrdersService plus { provide: OrdersRepository, useValue: fake }, then read the service with moduleRef.get(OrdersService).

solid answer

~40 s

`Test.createTestingModule()` from `@nestjs/testing` accepts the same metadata object `@Module()` takes (`imports`, `controllers`, `providers`) and returns a `TestingModuleBuilder`. Its `compile()` is asynchronous: it scans that metadata, builds every provider through Nest's injector and resolves to a `TestingModule`. For an `OrdersService` that injects an `OrdersRepository`, I register the service plus a custom provider such as `{ provide: OrdersRepository, useValue: fakeRepo }`, await `compile()`, and call `moduleRef.get(OrdersService)`; Nest hands the fake to the constructor exactly as it would the real class. If I forget a dependency, `compile()` rejects with the same "Nest can't resolve dependencies" error the app would throw at boot, so the test checks the wiring as well as the logic. A plain `new OrdersService(fakeRepo)` is faster but proves nothing about that wiring.

code

typescript · 24 lines
typescript
import { Test, TestingModule } from '@nestjs/testing';
import { OrdersService } from './orders.service.js';
import { OrdersRepository } from './orders.repository.js';

describe('OrdersService', () => {
  let service: OrdersService;

  beforeEach(async () => {
    const fakeRepo = { findAll: async () => [{ id: 1, total: 40 }] };

    const moduleRef: TestingModule = await Test.createTestingModule({
      providers: [
        OrdersService,
        { provide: OrdersRepository, useValue: fakeRepo },
      ],
    }).compile();

    service = moduleRef.get(OrdersService);
  });

  it('returns the orders the repository holds', async () => {
    expect(await service.findAll()).toEqual([{ id: 1, total: 40 }]);
  });
});

go deeper

for a junior

Recall that the metadata matches @Module(), that compile() must be awaited, and that a { provide, useValue } entry injects the fake.

for a middle

Explain what compile() actually does (scan, apply overrides, instantiate) and when overrideProvider or useMocker beats listing providers by hand.

for a senior

Show where these tests stop: they catch broken wiring at compile time but never exercise routing or the request pipeline.

for a principal

Discuss how much of a codebase's service coverage should go through the container versus direct construction, weighing speed against catching wiring breaks early.

## What the testing module is A NestJS application is a graph of **modules**, each declaring `providers` (injectable classes or values), `controllers` and `imports`. At boot, Nest scans that graph, works out each class's constructor dependencies and creates the instances. The `@nestjs/testing` package lets a test run the same machinery on a graph you choose. - `Test.createTestingModule(metadata)` takes **the same metadata object** you would pass to `@Module()` and returns a `TestingModuleBuilder`. Behind the scenes it wraps that metadata in a root module, which error messages call `RootTestModule`. - The builder collects changes (overrides, an auto-mocker, a logger) but creates nothing yet. - `compile()` is **asynchronous**. It scans the graph, applies any overrides, instantiates the providers and resolves to a `TestingModule`. A `TestingModule` is an application context: it offers the same `get()`, `resolve()` and `select()` API as a module reference, plus `createNestApplication()` for end-to-end tests. ## Building a unit test step by step Suppose `OrdersService` receives an `OrdersRepository` through its constructor and you want to test the service without a real data store. 1. Write a **fake** with the methods the service calls, for example an object whose `findAll()` resolves to a fixed list. 2. Call `Test.createTestingModule({ providers: [...] })`, listing `OrdersService` and a **custom provider** `{ provide: OrdersRepository, useValue: fakeRepo }`. The `provide` key is the injection token the service asks for; `useValue` is what Nest hands over. 3. `await` the `compile()` call. Forgetting `await` leaves you holding a Promise, and the next line fails. 4. Read the instance with `moduleRef.get(OrdersService)` and exercise it. ```typescript const moduleRef = await Test.createTestingModule({ providers: [ OrdersService, { provide: OrdersRepository, useValue: fakeRepo }, ], }).compile(); const service = moduleRef.get(OrdersService); ``` ## Ways to supply the fake | Approach | Where it goes | Typical use | |---|---|---| | Custom provider in `providers` | the metadata you pass in | a small, hand-built graph for one class | | `overrideProvider(OrdersRepository).useValue(fake)` | chained on the builder | importing a real module and swapping one provider inside it | | `useMocker(factory)` | chained on the builder | many dependencies: the factory is asked only for tokens Nest cannot resolve | `useMocker()` receives the missing token and returns a stand-in. If it returns nothing for a token, `compile()` still fails with the original dependency error, so a forgotten case shows up as a failure rather than as an empty object. ## Reading instances back - `get(token)` returns the **static** (singleton) instance of a provider or controller. By default it searches the whole graph; `get(token, { strict: true })` limits the search to the module currently selected. - `select(SomeModule)` moves into a particular module of the graph, which you combine with `strict: true` when two modules register the same token. - `resolve(token)` is for **request-scoped and transient** providers; `get()` throws for those. That difference is a topic of its own. ## What compile() proves, and what it does not Using the testing module instead of `new OrdersService(fakeRepo)` buys you one thing a direct constructor call cannot: **Nest's own resolution of the constructor**. A missing provider, a module that does not export what another imports, or an injection token that does not match all fail inside `compile()` with the same "Nest can't resolve dependencies of ..." error, naming the class and the missing argument, that the real app would print at startup. It does not prove anything about HTTP: no routes are registered and no request passes through guards, pipes or interceptors. That requires an application created from the compiled module, which is the end-to-end side of this package. ## Logging during tests By default the testing module installs a quiet logger: info, warning and debug messages are dropped while errors still print, so startup chatter does not flood test output. When a CI run needs more, chain `setLogger()` on the builder with any object that implements Nest's `LoggerService` interface, for example a `ConsoleLogger`, before calling `compile()`. ## Common mistakes - Listing only `OrdersService` and expecting Nest to invent the repository: without a provider (or `useMocker`), `compile()` rejects. - Calling `get()` before awaiting `compile()`. - Building one module for the whole file in a `beforeAll` and letting tests mutate the same fake; recreating it in `beforeEach` keeps tests independent. - Importing the full root module into a unit test, which pulls in every real dependency the test meant to avoid.

  • In NestJS testing, what does useMocker() do when your factory returns undefined for a token?
    `useMocker()` is consulted only when Nest cannot resolve a dependency. If the factory returns a value, Nest registers it as that token's instance, so `moduleRef.get(Token)` returns the mock too. If it returns `undefined` (or anything falsy), the original resolution error is rethrown and `compile()` rejects, so an unhandled token is reported instead of silently injected as nothing.
  • Why might a team still write some NestJS service tests as plain new OrdersService(fake) calls?
    A direct constructor call skips scanning and the injector, so it is faster and has no framework setup. It fits pure logic whose wiring is already covered elsewhere. What it gives up is the check that the module graph resolves: a missing export or wrong token passes a constructor test and fails only when the app or an end-to-end test boots.

  • Test.createTestingModule() needs a special testing metadata format
  • compile() is synchronous, so its result can be used directly
  • Nest creates an empty stub for any dependency you did not register
  • moduleRef.get() works the same for request-scoped providers
  • A testing module also registers the HTTP routes
open as a page

In a NestJS e2e test, what do createNestApplication(), app.init(), getHttpServer() and app.close() each contribute to a Supertest request?

level: middleimportance: must knowfreq 58%

basics

~20 s

createNestApplication() wraps the compiled TestingModule in an INestApplication on the Express adapter; app.init() registers middleware and routes and runs init hooks; getHttpServer() gives Supertest the Node server; app.close() runs shutdown hooks and closes the server.

open as a page

In a NestJS TestingModuleBuilder, how do overrideProvider, overrideGuard and overrideModule differ, and what can each be replaced with?

level: middleimportance: must knowfreq 55%

basics

~20 s

overrideProvider swaps a registered provider; overrideGuard (like overrideInterceptor, overrideFilter, overridePipe) swaps an enhancer bound by decorator. Both take useValue, useClass or useFactory({ factory, inject }); overrideModule takes useModule. An override whose token matches nothing is silently ignored.

open as a page

In a NestJS TestingModule, why does get() throw for a request-scoped provider, and how do resolve() and a context ID help?

level: middleimportance: should knowfreq 30%

basics

~20 s

get() returns only static singletons, so a request-scoped or transient provider, or anything depending on one, throws InvalidClassScopeException. resolve() builds the instance in a DI sub-tree; each call gets a new one unless you pass the same contextId.

open as a page

In a NestJS e2e test, why does overrideGuard(AppAuthGuard) leave orders requests failing with 403 when that guard is registered through APP_GUARD, and how do you fix it?

level: seniorimportance: should knowfreq 38%

basics

~10 s

{ provide: APP_GUARD, useClass: AppAuthGuard } is stored under a generated APP_GUARD token, so no override keyed by AppAuthGuard matches. Register AppAuthGuard as a provider, point APP_GUARD at it with useExisting, then call overrideProvider(AppAuthGuard).

open as a page