What does each NestJS testing layer prove?
Each layer should answer one question that the layer below it cannot. If two layers prove the same thing, one of them is wasted runtime.
scope database externals
E2E supertest -> app.init() -> guards/pipes/interceptors/
filters -> controller -> service -> repository ----> [real Postgres] overridden
Integration Test.createTestingModule -> service -> repository ----> [real Postgres] overridden
Unit domain logic / single provider none none needed
| Layer | Proves | Real DB | Speed | Typical failure it catches |
|---|---|---|---|---|
| Unit | Business rules are correct in isolation | No | Milliseconds | Wrong calculation, bad state transition |
| Integration | A module's providers, queries and transactions work against the real schema | Yes | Seconds | Constraint violation, broken join, missing index, wrong isolation |
| E2E | The HTTP contract holds through the full request pipeline | Yes | Slowest | Guard not applied, DTO validation skipped, filter mapping wrong status |
Unit tests target pure domain logic and single providers. Prefer passing real values over mocking collaborators, because mock-heavy unit tests often only confirm that the mocks were configured the way the test expects.
Integration tests are where most of the confidence comes from. This strategy fits backend and platform teams whose services sit on relational databases, where bugs tend to live in SQL, constraints and transaction boundaries. An in-memory fake cannot reproduce those.
Keep E2E tests few and limit them to critical paths such as authentication, payments and core writes. When an HTTP-level test fails, the cause could be in any of a dozen layers. A failing integration test points much closer to the root cause.
+------------------------------------------------------------------+
| E2E: supertest --HTTP--> app.init() |
| [guards] -> [pipes] -> [interceptors] -> [exception filters] |
| | |
| v |
| [controller] |
| | |
| +-------------------------------v------------------------------+ |
| | Integration: Test.createTestingModule() | |
| | v | |
| | [api client] <--- [service] ---> [repository] | |
| | | +-----------------------+ | | |
| | | | Unit: domain logic | | | |
| | | | single provider | | | |
| | | | no DB, real values | | | |
| | | +-----------------------+ | | |
| +---------v------------------------------------v---------------+ |
| | | |
+------------v------------------------------------v----------------+
+------------------+ +------------------+
| external APIs | | real Postgres |
| overridden via | | (test schema) |
| overrideProvider | | migrated per run |
+------------------+ +------------------+
Unit tests sit inside the integration module, the integration module sits inside the full HTTP pipeline that E2E tests drive, and both outer layers hit the real Postgres while external APIs are overridden.
When should you override providers in the Testing Module?
Test.createTestingModule() takes the same metadata as a regular @Module(), so you can import your real AppModule or a feature module and get the full dependency graph. Before calling compile(), you can chain overrideProvider(Token) and replace that provider. useValue swaps in a fixed object, such as a stub with jest.fn() methods. useClass swaps in a class that Nest instantiates and injects like any other provider. Everything you don't override stays real.
Override only the true system boundaries: third-party APIs, the clock, and message brokers you don't own. These are the dependencies that make a test slow, flaky, or dependent on someone else's uptime. A payment gateway sandbox can rate-limit you mid-run. A real clock makes expiry logic depend on when CI happens to run.
Repositories and ORM clients don't belong on that list. A mocked repository returns whatever you told it to, so it can't catch the problems that live in the database: a misspelled column, a missing unique constraint, a ON DELETE rule you forgot, or a transaction that doesn't roll back.
Both directions fail. Override too much and an integration test quietly becomes a unit test that passes while production breaks. Override too little and the suite depends on external services, producing failures nobody can reproduce.
The example below overrides a PaymentGatewayClient with useValue and a Clock token with useClass pointing at a fixed-time implementation. The real OrdersRepository stays in place against Postgres.
import { Test, TestingModule } from '@nestjs/testing';
import { AppModule } from '../src/app.module';
import { PaymentGatewayClient } from '../src/payments/payment-gateway.client';
import { Clock } from '../src/common/clock'; // abstract class used as the DI token
import { OrdersService } from '../src/orders/orders.service';
import { OrdersRepository } from '../src/orders/orders.repository';
// Fixed time so expiry logic does not depend on when CI happens to run
class FixedClock implements Clock {
now(): Date { return new Date('2026-01-15T10:00:00Z'); }
}
describe('OrdersService (integration)', () => {
let moduleRef: TestingModule;
const gateway = { charge: jest.fn().mockResolvedValue({ id: 'ch_test_123', status: 'succeeded' }) };
beforeAll(async () => {
// AppModule wires the real OrdersRepository to the test Postgres (DATABASE_URL from the test env)
moduleRef = await Test.createTestingModule({ imports: [AppModule] })
.overrideProvider(PaymentGatewayClient).useValue(gateway) // third-party API: a true boundary
.overrideProvider(Clock).useClass(FixedClock) // wall-clock time: a true boundary
.compile();
await moduleRef.init();
});
afterAll(() => moduleRef.close());
it('persists a paid order with the expected expiry', async () => {
const orders = moduleRef.get(OrdersService);
const order = await orders.placeOrder({ customerId: 'cust_42', amountCents: 2500 });
expect(gateway.charge).toHaveBeenCalledWith(expect.objectContaining({ amountCents: 2500 }));
// Read back through the real repository: exercises columns, constraints and defaults in Postgres
const saved = await moduleRef.get(OrdersRepository).findById(order.id);
expect(saved?.status).toBe('paid');
expect(saved?.expiresAt).toEqual(new Date('2026-01-15T10:30:00Z'));
});
});
An integration test that replaces only the payment gateway (useValue) and the clock (useClass) while the real OrdersRepository runs against Postgres.
How do you run a real Postgres database with Testcontainers for Node?
Unit and integration tests both need a database, and the most faithful one is the engine you run in production. Testcontainers for Node starts a disposable Postgres container from Jest's globalSetup file, and the matching globalTeardown file stops it. Both files are registered under the globalSetup and globalTeardown keys in the Jest config. Jest runs globalSetup once, before any worker starts. If you store the container reference on globalThis, the teardown file can read it back and call stop().
Don't pin a host port. Let the library map Postgres to a free ephemeral port, then read the connection URI from the started container and write it to process.env.DATABASE_URL. Jest spawns workers after setup completes, so they inherit that variable. Your ConfigModule then reads it the same way it would in any other environment. This avoids collisions when a developer already has Postgres on 5432 or when CI runs several jobs on one host.
Before setup returns, apply the schema with your real migrations. Use the same migration runner your deploy pipeline uses, and keep ORM schema synchronization off. If you let the ORM auto-sync the schema, the tests pass against a schema your migrations might never produce. Running the migrations instead means a broken or out-of-order migration fails the suite before it can fail a deploy.
You also need to decide how many containers to run:
- One container per test run is cheap: you pay startup and migration once. The cost is that every test file shares a single database, so isolation becomes your responsibility.
- One container per test file removes that coupling. The cost is a container boot and a full migration run for each file, and that overhead grows with the number of files.
// test/global-setup.ts: runs once, before Jest starts any worker
import { PostgreSqlContainer } from '@testcontainers/postgresql';
import { DataSource } from 'typeorm';
export default async function globalSetup() {
// No fixed host port: Testcontainers maps 5432 to a free ephemeral port
const container = await new PostgreSqlContainer('postgres:16-alpine').start();
// Workers are spawned after this function returns, so they inherit this
process.env.DATABASE_URL = container.getConnectionUri();
// Apply the schema with the same migrations production runs, not auto-sync
const ds = new DataSource({
type: 'postgres',
url: process.env.DATABASE_URL,
migrations: ['src/migrations/*.ts'],
synchronize: false,
});
await ds.initialize();
await ds.runMigrations(); // a broken migration fails the suite here
await ds.destroy();
// globalTeardown runs in this same process, so it can read this back
(globalThis as any).__PG_CONTAINER__ = container;
}
// test/global-teardown.ts
export default async function globalTeardown() {
await (globalThis as any).__PG_CONTAINER__?.stop();
}
// jest.config.ts (excerpt)
// export default {
// preset: 'ts-jest',
// globalSetup: '<rootDir>/test/global-setup.ts',
// globalTeardown: '<rootDir>/test/global-teardown.ts',
// };
A Jest globalSetup that starts one Postgres container per test run on a free port, exports its URI as DATABASE_URL, and runs the real TypeORM migrations, plus the globalTeardown that stops the container and the Jest config entries that register both files.
How should you isolate test data between tests and Jest workers?
Three isolation approaches are common. They differ mainly in what happens at commit time.
| Approach | Speed | Faithful to production | Own transactions / multiple connections | Commit-time behavior |
|---|---|---|---|---|
| Rollback per test | Fastest | Low | Inner transactions become savepoints or fail. Other connections cannot see uncommitted rows. | Deferred constraints and deferred triggers never fire |
| Truncate between tests | Moderate, slows as tables grow | High | Works, because data is really committed | Fires as in production |
| Schema or database per Jest worker | Migration cost once per worker | High | Works | Fires as in production |
Rollback is attractive because it is cheap. It breaks once a service opens its own transaction, reads through a second pool connection, or relies on a constraint checked at COMMIT. In those cases the test passes against behavior that production never shows.
Truncation keeps real commits, but it needs care:
- Statement count. Every new table adds to the reset step.
- Foreign keys. Row-by-row
DELETEmust follow foreign-key order. - Cascade rules. A cascade rule can silently empty tables you meant to keep, such as seeded reference data.
To avoid ordering bugs, truncate every table in one statement rather than one table at a time.
Parallel workers that share one database interfere with each other. Worker A truncates while worker B is mid-assertion, or both insert the same unique email. Which test fails depends on scheduling, so the failure looks random and disappears when you rerun a single file. The fix is to derive a schema name from JEST_WORKER_ID, then create and migrate that schema once per worker.
Within that schema, build data with small factory functions that take overrides. Avoid large shared fixture files. With a factory, each test declares the rows it depends on, and editing one fixture can no longer break unrelated tests.
import { Client } from 'pg';
// Jest assigns each worker a JEST_WORKER_ID ("1", "2", ...). Default to "1" for --runInBand.
const workerId = process.env.JEST_WORKER_ID ?? '1';
export const schema = `test_w${workerId}`; // also point the app's DB config at this schema
// Run once per worker: create an isolated schema and migrate it.
export async function setupWorkerSchema(db: Client, migrate: (s: string) => Promise<void>) {
await db.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);
await db.query(`SET search_path TO ${schema}`);
await migrate(schema);
}
// Between tests: one statement listing every data table, so FK order doesn't matter.
// No CASCADE, so seeded reference tables are never emptied by accident.
export async function resetData(db: Client) {
await db.query('TRUNCATE orders, users RESTART IDENTITY');
}
type User = { id: number; email: string; name: string; role: string };
let seq = 0;
// Small factory: sensible defaults, and the test overrides only the fields it cares about.
export async function createUser(db: Client, overrides: Partial<Omit<User, 'id'>> = {}): Promise<User> {
seq += 1;
const u = { email: `user${seq}@example.test`, name: 'Test User', role: 'member', ...overrides };
const { rows } = await db.query<User>(
'INSERT INTO users (email, name, role) VALUES ($1, $2, $3) RETURNING *',
[u.email, u.name, u.role],
);
return rows[0];
}
// Usage in a test: the data dependency is visible right here.
// const admin = await createUser(db, { role: 'admin' });
Deriving a per-worker PostgreSQL schema from JEST_WORKER_ID, resetting it with a single TRUNCATE statement, and creating test rows with a small factory that takes overrides.
How do you make NestJS E2E tests match production bootstrapping?
Test.createTestingModule().compile() followed by createNestApplication() gives you a bare application. It does not run anything in main.ts. If main.ts calls useGlobalPipes(new ValidationPipe({ whitelist: true })), setGlobalPrefix('api') and enableVersioning(), the test app has none of that. Your E2E suite then hits /users instead of /api/v1/users, accepts payloads that production rejects, and returns raw exception bodies where production returns the shape your filter produces. All the tests pass, and none of them check the HTTP contract that clients actually call.
Extract a shared configureApp
Move every global setting into a configureApp(app: INestApplication) function. Call it from main.ts before listen(), and from the E2E bootstrap before app.init(). Global configuration must be registered before initialization, so the order matters. Once both entry points call the same function, adding a filter or changing a pipe option updates both automatically. You can also register pipes and filters as APP_PIPE and APP_FILTER providers inside a module. The testing module picks those up without any extra step, which removes part of this problem.
Shut down cleanly
In afterAll, call await app.close(). This runs the shutdown lifecycle hooks, so ORM modules can release their connection pools. Pools or clients that you created yourself, such as a raw pg pool used for seeding, must be ended explicitly. Stop the container last, after nothing holds a connection to it. If you skip any of these steps, Jest reports open handles or the worker never exits. Run once with --detectOpenHandles to find the leak, rather than masking it with --forceExit.
What are the alternatives to Testcontainers, and when should you avoid it?
Testcontainers is not the only way to get a database into a test run. Each alternative trades startup cost against how closely it matches production.
| Approach | Startup cost | Fidelity to production Postgres | Isolation | Main risk |
|---|---|---|---|---|
| In-memory or embedded substitute | Lowest | Low | Per process | Passes tests that fail on the real engine |
| CI service container | Low, provisioned before the job | High, if the image matches production | Per job | Version drift between the CI config and production |
| Shared long-lived test database | None per run | High | Weak | Cross-run data leaks and flaky tests |
| Fully mocked repositories | None | None | Total | Tests only the mock's behaviour |
In-memory and embedded substitutes start faster because there is no network and no container. They are still a different engine. SQL dialects diverge on upserts, RETURNING and window functions. Row-level locking and SELECT ... FOR UPDATE may not exist or may behave differently. Types such as jsonb, arrays and enums are often emulated or missing. A test that exercises a concurrent update or a JSON path query can go green against the substitute and fail against Postgres.
Avoid Testcontainers in three cases:
- Restricted CI. Some runners forbid privileged Docker or Docker-in-Docker.
- Pure logic. Domain functions with no I/O belong in fast unit tests. A container adds seconds and gives no extra confidence.
- No Docker access. Some teams cannot run Docker locally or in CI.
In the first and third cases, use a pre-provisioned service container. Keep the same environment-variable contract described earlier: DATABASE_HOST, DATABASE_PORT and credentials. Have the test bootstrap skip starting a container whenever those variables are already set. The suite, migrations and isolation strategy stay the same. Only the source of the connection details changes.
How much do real-database tests cost, and how do they save engineering time?
Illustrative estimate (assumed numbers, not a benchmark)
Assume container startup takes 8 s, each Jest worker gets its own database, 4 workers run in parallel, the suite has 200 integration tests at 150 ms each, and 300 unit tests run at 5 ms each.
- Wall time ≈ startup + (tests × per-test duration) ÷ workers
- Integration: 8 + (200 × 0.15) ÷ 4 = 8 + 7.5 ≈ 15.5 s
- Unit: (300 × 0.005) ÷ 4 ≈ 0.4 s
Put in your own numbers. At small suite sizes, startup is most of the cost. As the suite grows, per-test duration matters more. That is why per-worker databases and transaction rollbacks matter more than shaving a second off container boot.
Making it work in CI
- Use a runner with a Docker daemon. Some hosted runners have one and some do not, so confirm this before you design the pipeline around containers.
- Cache images. Either cache the Postgres image or pull it from a nearby registry. Pulling the image on every run can cost more than starting it.
- Split the suites into separate Jest projects. Make unit, integration and E2E their own projects. Developers can then run unit tests alone, and CI can run them as a fast first gate.
- Give each project its own timeout. Set it in the project's config or setup file. Container startup on a cold runner can take far longer than the default Jest timeout, and that produces flaky failures that look like real bugs.
Where the time comes back
Real-database tests catch problems that mocks cannot see:
- migrations that fail against existing schema
- violated unique and foreign-key constraints
- isolation-level surprises inside transactions
Each of these is cheaper to fix in CI than in an incident. You also stop maintaining mocks that drift from the real repository behaviour. Over time, you spend less effort debugging failures that appear in production but never appeared in tests.
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, 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.