How does the NestJS testing module work?
Test.createTestingModule() takes the same metadata you pass to @Module(): imports, providers, controllers. It returns a builder, not a mock framework. Calling compile() builds a real Nest dependency injection container: it walks every constructor, resolves each injection token, and instantiates providers in dependency order. module.get() then hands you the instance the container created, wired exactly as it would be at runtime.
Because resolution is real, a missing dependency is an error at compile time, not a silent undefined. Nest reports which provider could not resolve which constructor argument. This catches problems early: a forgotten export, an injection token that doesn't match, or a circular import. The same checks run when the application boots.
The unit/integration line is a question of how much of the real graph you let compile. A unit test registers one provider and supplies stubs for each of its constructor dependencies. An integration test imports the real feature module and uses overrideProvider() only at the edges that leave the process:
OrdersModule (imported for real)
┌───────────────────────────────────────────────┐
│ OrdersController │
│ │ │
│ ▼ │
│ OrdersService ──► PricingService (real) │
│ │ │ │ │
└────┼──────┼──────┼────────────────────────────┘
✂ ✂ ✂ ← overrideProvider cut points
▼ ▼ ▼
PaymentsHttpClient EventPublisher OrdersRepository
(remote API) (broker) (database)
Everything above the cut runs as written, including pipes, guards, and the service-to-service wiring. Only I/O is replaced. That boundary is what makes a test an integration test rather than a large unit test.
import { Test, TestingModule } from '@nestjs/testing';
import { OrdersModule } from './orders.module';
import { OrdersService } from './orders.service';
import { PaymentsHttpClient } from './payments-http.client';
import { EventPublisher } from './event-publisher';
import { OrdersRepository } from './orders.repository';
describe('OrdersService (integration)', () => {
let moduleRef: TestingModule;
// Stubs stand in only for the edges that leave the process.
const payments = { charge: jest.fn().mockResolvedValue({ status: 'captured' }) };
const events = { publish: jest.fn().mockResolvedValue(undefined) };
const repo = { save: jest.fn(async (order) => ({ id: 'ord_123', ...order })) };
beforeEach(async () => {
moduleRef = await Test.createTestingModule({
// Real graph: OrdersController, OrdersService, PricingService.
imports: [OrdersModule],
})
.overrideProvider(PaymentsHttpClient).useValue(payments) // remote API
.overrideProvider(EventPublisher).useValue(events) // broker
.overrideProvider(OrdersRepository).useValue(repo) // database
.compile(); // resolves every constructor; fails here if a token is missing
});
afterEach(async () => {
jest.clearAllMocks();
await moduleRef.close();
});
it('prices, charges, persists and publishes an order', async () => {
// Same instance the container wired, with real PricingService inside.
const service = moduleRef.get(OrdersService);
const order = await service.placeOrder({ sku: 'SKU-42', quantity: 2 });
expect(payments.charge).toHaveBeenCalledTimes(1);
expect(repo.save).toHaveBeenCalledTimes(1);
expect(events.publish).toHaveBeenCalledWith('order.placed', expect.objectContaining({ id: order.id }));
});
});
An integration test that compiles the real OrdersModule graph and uses overrideProvider() only at the three I/O cut points from the diagram, then retrieves the wired OrdersService with moduleRef.get().
How do you write a unit test for a single NestJS provider?
A unit test drops the database entirely. Register the class under test as a real provider and register every collaborator as a stand-in: { provide: PaymentsGateway, useValue: { charge: jest.fn() } }. For string or symbol tokens injected with @Inject(), use the same token in provide. After compile(), pull the service out with module.get() and set return values per test with mockResolvedValue or mockReturnValue.
An untyped object literal drifts. If someone renames charge to authorize, the mock keeps compiling and the test keeps passing. Typing it helps. Declare the mock as Partial<PaymentsGateway> and cast it when you register it. A better option is a small factory that returns jest.Mocked<Pick<PaymentsGateway, 'charge'>>, which makes the compiler check method names and signatures. This is still not airtight. The cast suppresses errors about methods you left out, and the type system cannot check that your mocked return values match what the real gateway returns at runtime.
If the class needs nothing from the container, such as lifecycle hooks, request scoping or token resolution you want to exercise, skip the testing module and write new OrderService(gatewayMock, repoMock). No module compilation happens, so these tests run faster and fail with a plain stack trace that is easier to read.
The trade-off is that heavily mocked tests verify your assumptions about collaborators, not the collaborators themselves. They tell you the service calls charge with the right arguments. They cannot tell you that charge throws on a declined card. Keep unit tests for branching logic and rely on the integration layer to test how the real collaborators behave.
import { Test } from '@nestjs/testing';
import { OrderService } from './order.service';
import { PaymentsGateway } from './payments.gateway';
// Typed factory: the compiler checks that 'charge' exists and matches its signature.
function createGatewayMock(): jest.Mocked<Pick<PaymentsGateway, 'charge'>> {
return { charge: jest.fn() };
}
describe('OrderService', () => {
let service: OrderService;
let gateway: jest.Mocked<Pick<PaymentsGateway, 'charge'>>;
beforeEach(async () => {
gateway = createGatewayMock();
const moduleRef = await Test.createTestingModule({
providers: [
OrderService,
// Cast hides methods we did not mock; this is the gap that remains.
{ provide: PaymentsGateway, useValue: gateway as unknown as PaymentsGateway },
],
}).compile();
service = moduleRef.get(OrderService);
});
it('charges the order total', async () => {
// This return value is our assumption, not the real gateway's behaviour.
gateway.charge.mockResolvedValue({ id: 'ch_test_123', status: 'succeeded' });
await service.placeOrder({ orderId: 'ord_42', amountCents: 2500 });
expect(gateway.charge).toHaveBeenCalledWith(2500, 'ord_42');
});
});
// No container features needed? Construct directly: no compile step, plainer stack traces.
describe('OrderService (plain constructor)', () => {
it('rejects zero-amount orders before charging', async () => {
const gateway = createGatewayMock();
const service = new OrderService(gateway as unknown as PaymentsGateway);
await expect(service.placeOrder({ orderId: 'ord_0', amountCents: 0 })).rejects.toThrow();
expect(gateway.charge).not.toHaveBeenCalled();
});
});
A typed gateway mock registered with useValue in a testing module, next to the same service built with new, showing that the mocked return values are assumptions.
How do you use overrideProvider in NestJS integration tests?
Start from the real feature module. Pass PaymentsModule to imports in Test.createTestingModule, so the dependency graph, decorators and provider wiring resolve the same way they do in production. Then replace only the outer edges, such as the payment gateway client, the mailer or the clock, with overrideProvider(Token). Follow it with .useValue() for a plain object of jest.fn() stubs, .useClass() for a hand-written fake, or .useFactory() when the fake needs injected dependencies. A string or symbol token works the same as a class: override 'PAYMENT_GATEWAY' or the exported symbol itself. Providers that were registered with useFactory are replaced the same way, because the override targets the token and not the recipe that built it.
After compile(), call module.get(Token) to fetch the instance Nest actually injected, and assert against it. get() only works for singletons. A request-scoped or transient provider needs await module.resolve(Token), and every call can return a different instance.
Overrides reach tokens and nothing else. An object built inside a factory, a client created with new in a constructor, or a connection opened inside a forRoot/forRootAsync module is never a provider you can swap. In those cases, override the config token the factory reads, or move the dependency behind its own injectable token.
Avoid importing AppModule here. It loads configuration, opens database connections, starts scheduled jobs and registers queue consumers. To keep the test running you end up overriding a dozen providers, and at that point the test is mostly measuring your mocks.
import { Test, TestingModule } from '@nestjs/testing';
import { PaymentsModule } from './payments.module';
import { PaymentsService } from './payments.service';
import { MailerService } from '../mailer/mailer.service';
import { CLOCK } from '../common/clock.token'; // export const CLOCK = Symbol('CLOCK');
import { FakeMailer } from '../../test/fake-mailer';
describe('PaymentsModule (integration)', () => {
let moduleRef: TestingModule;
const gateway = { charge: jest.fn().mockResolvedValue({ id: 'ch_test_123', status: 'succeeded' }) };
beforeEach(async () => {
moduleRef = await Test.createTestingModule({
imports: [PaymentsModule], // real wiring, guards, pipes, interceptors
})
// String token, even if PaymentsModule registers it with useFactory
.overrideProvider('PAYMENT_GATEWAY').useValue(gateway)
// Hand-written fake that records sent mail
.overrideProvider(MailerService).useClass(FakeMailer)
// Symbol token; a factory is useful when the fake needs injected values
.overrideProvider(CLOCK).useFactory({ factory: () => ({ now: () => new Date('2025-01-01T00:00:00Z') }) })
.compile();
});
it('charges through the gateway and emails a receipt', async () => {
// Use resolve() instead if PaymentsService is request-scoped or transient
const payments = moduleRef.get(PaymentsService);
await payments.checkout({ orderId: 'order_42', amountCents: 1999 });
// get() returns the instance Nest actually injected
expect(moduleRef.get('PAYMENT_GATEWAY').charge).toHaveBeenCalledWith(
expect.objectContaining({ amountCents: 1999 }),
);
expect(moduleRef.get(MailerService)).toBeInstanceOf(FakeMailer);
});
afterEach(() => moduleRef.close());
});
An integration test imports the real PaymentsModule and overrides only its edges: a string-token gateway with useValue, a class with useClass, and a symbol-token clock with useFactory. It then uses get() to fetch the injected mock and assert on its calls.
How do you override guards, interceptors, pipes and filters?
Guards, interceptors, pipes and filters attached with @UseGuards(), @UseInterceptors(), @UsePipes() and @UseFilters() have dedicated override methods on the testing module builder: overrideGuard(), overrideInterceptor(), overridePipe() and overrideFilter(). They take the class referenced in the decorator and accept useValue, useClass or useFactory, like overrideProvider(). To bypass authentication in a controller test, override the auth guard with an object whose canActivate returns true. If the handler reads the user from the request, have it attach a fixed user as well. The controller logic then runs as if a valid token had been presented, and you don't have to mint JWTs in test setup.
These methods match on enhancer metadata attached to controllers and handlers. A guard registered globally through { provide: APP_GUARD, useClass: JwtAuthGuard } is not referenced in that metadata. It is a provider registered under the APP_GUARD token, so overrideGuard(JwtAuthGuard) has nothing to replace and the real guard keeps rejecting requests.
To make a global guard overridable, register the guard class as an ordinary provider and point APP_GUARD at it with useExisting. Then call overrideProvider(JwtAuthGuard) in the test, and the global registration resolves to your replacement. The code example below shows both forms: overrideGuard() for a decorator-scoped guard and overrideProvider() for the global one.
Enhancers registered with app.useGlobalGuards() or similar calls in main.ts are a separate case. They never enter the testing module, so tests only apply them if your test bootstrap calls them too.
import { Test, TestingModule } from '@nestjs/testing';
import { ExecutionContext } from '@nestjs/common';
import { AppModule } from '../src/app.module';
import { OrdersController } from '../src/orders/orders.controller';
import { OrdersService } from '../src/orders/orders.service';
import { JwtAuthGuard } from '../src/auth/jwt-auth.guard';
// Stub guard: lets every request through and attaches a fixed user
// so handlers that read req.user still work without minting a JWT.
const allowAll = {
canActivate: (ctx: ExecutionContext) => {
ctx.switchToHttp().getRequest().user = { id: 'user-123', roles: ['admin'] };
return true;
},
};
// Form 1: guard attached with @UseGuards(JwtAuthGuard) on the controller.
// overrideGuard() matches the class referenced in that decorator metadata.
async function buildScoped(): Promise<TestingModule> {
return Test.createTestingModule({
controllers: [OrdersController],
providers: [{ provide: OrdersService, useValue: { findAll: jest.fn() } }],
})
.overrideGuard(JwtAuthGuard)
.useValue(allowAll)
.compile();
}
// Form 2: global guard. AppModule registers it as an ordinary provider:
// providers: [JwtAuthGuard, { provide: APP_GUARD, useExisting: JwtAuthGuard }]
// APP_GUARD aliases the JwtAuthGuard provider, so overriding that provider
// replaces the global guard. overrideGuard(JwtAuthGuard) would not.
async function buildGlobal(): Promise<TestingModule> {
return Test.createTestingModule({ imports: [AppModule] })
.overrideProvider(JwtAuthGuard)
.useValue(allowAll)
.compile();
}
Bypassing authentication two ways: overrideGuard() for a guard attached with @UseGuards(), and overrideProvider() for a global guard that AppModule registers as a provider and exposes through APP_GUARD with useExisting.
How do you run HTTP-level integration tests with supertest?
To close that gap, build a real application instance from the compiled module. After Test.createTestingModule({ imports: [AppModule] }).compile(), call moduleRef.createNestApplication() on the result. This creates the same kind of INestApplication that NestFactory.create() returns in main.ts, with any provider overrides you declared already in place.
The application is still incomplete at this point. Everything main.ts does to the app after creating it lives outside the module graph. That includes app.useGlobalPipes(new ValidationPipe(...)), app.setGlobalPrefix('api'), app.enableVersioning(...) and any global guards or filters. The testing module never sees those calls.
A test suite that skips them can pass while production behaves differently. Two examples:
- Routes answer at
/usersin tests but at/api/v1/usersin production. - A payload with unknown fields passes in tests because the
whitelistoption was never applied.
The fix is to move that setup into a single exported function, such as configureApp(app). Call it from main.ts before listen(), and call it from the test setup before init(). Both paths then run the same code, and a new global pipe can't reach one path and miss the other.
Then run await app.init(). This runs lifecycle hooks such as onModuleInit and registers the routes, but it does not bind a port. Pass app.getHttpServer() to supertest's request(). When the server is not already listening, supertest binds it to an ephemeral port, so parallel Jest workers don't compete for a fixed port.
In afterAll, call await app.close(). This runs shutdown hooks and releases database connections and other handles. Without it, Jest may warn about open handles or fail to exit cleanly.
How should you structure Jest NestJS test suites for isolation and CI?
Where the module is created matters as much as closing it. Compiling a fresh module in beforeEach gives each test its own provider instances, so a test that mutates state cannot affect the next one. The cost is compile time on every test. Compiling once in beforeAll is faster, but tests then share singletons and mock call history.
| Setup | Isolation | Runtime | Good fit |
|---|---|---|---|
beforeEach fresh module |
Full per test | Slower, compiles every test | Unit specs with stateful providers |
beforeAll shared module |
Shared instances | Faster, compiles once | Integration and e2e specs with a real app |
If you share a module, reset mocks between tests. You can call jest.clearAllMocks() in afterEach, or set clearMocks: true (and restoreMocks: true if you use jest.spyOn) in the Jest config so you don't forget it in a new file. In both setups, call close() on the module or app. If Jest still hangs, --detectOpenHandles shows what is holding the process open.
Split unit and integration specs. Use *.spec.ts beside the source for unit tests, and put *.e2e-spec.ts files under test/ with their own config passed via --config. Developers run the fast unit suite on every save. CI runs both suites as separate jobs, and the slower one can be gated on the first.
Put the module setup and shared overrides in one helper, for example createTestingApp(overrides). Each spec then lists only the overrides it changes, instead of copying the full setup.
Request-scoped providers and forwardRef cycles make setup harder. Request-scoped providers need resolve() rather than get(), and circular dependencies make overrides hard to reason about. When either one dominates your test setup, the module design usually needs another look.
When should you mock, and what are the alternatives to overrideProvider?
The decision rule is simple. Override a dependency when it is slow, nondeterministic, or outside the process boundary: payment gateways, email senders, clocks, random IDs, message brokers. Keep domain logic and module wiring real, because DI configuration errors, missing exports, and guard ordering only appear when Nest assembles the actual module graph.
| Approach | What it verifies | Cost | Best fit |
|---|---|---|---|
new Service(dep) |
Pure logic | Lowest | Calculations, mappers, policies |
| Mocked providers in a testing module | Provider behaviour plus DI resolution | Low | Services with a few collaborators |
| Real feature module, edge overrides | Wiring, guards, pipes, validation | Moderate | Controllers and cross-module flows |
| Real database in a container | Queries, migrations, constraints | Highest | Complex queries, transactions, locking |
A mocked repository confirms that you called a method. It cannot confirm that the generated SQL is correct, that a unique constraint fires, or that a transaction isolates rows. When those queries carry business risk, run them against a real database engine.
That confidence costs something. You pay for container startup, a CI runner that supports containers, migration runs, and slower feedback during development. As an illustrative estimate, assume a unit suite finishes in a few seconds and a container needs 10–20 seconds to start and migrate. Starting the container once per run and truncating tables between tests keeps that overhead from growing with each test file.
Teams with heavy module wiring, layered guards, and validation pipes benefit most from real-module tests. For pure logic or small services with one or two dependencies, skip the testing module and use new.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to nestjs testing module, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.