What is NestJS integration testing?

NestJS integration testing runs several real parts of an application together inside a Nest testing module. This includes module wiring, dependency injection, pipes, guards, repositories and a real database. A unit test isolates one class and replaces its collaborators. An integration test keeps the collaborators real and replaces only what lies outside your process.

Both kinds of test use the same tooling. @nestjs/testing provides Test.createTestingModule(), and projects generated by the Nest CLI come configured for Jest. The design question this article answers is which dependencies stay real and which get replaced. The short answer:

  • Mock collaborators when you are testing decision logic.
  • Use a real database, on the same engine as production, when you are testing persistence.
  • Use fakes for third-party systems.

How does a NestJS integration test work?

A database-backed integration test follows the same sequence every run:

  1. Provision the database. Start a container running the same engine and major version as production.
  2. Apply the schema. Run the real migration files against the empty database rather than letting the ORM sync the schema from entities.
  3. Build the testing module. Call Test.createTestingModule() with the feature modules under test and a database module that reads config the same way production does.
  4. Override the edges. Use overrideProvider() to swap out dependencies that leave the process, such as HTTP clients, queue producers and mailers.
  5. Compile and run. Call .compile(). Then either get providers with get() and call them directly, or call createNestApplication() and init() and send HTTP requests to the app.
  6. Reset state. Before each test, reset the database by transaction rollback, truncation, or a schema per Jest worker.
  7. Tear down. Call app.close() or moduleRef.close() so connection pools and other handles shut down.

The sections below cover each step in detail.

Who should use real-database integration tests?

  • Teams whose NestJS services own persistence logic. This means custom queries, query builders, transactions, unique and foreign-key constraints, soft deletes, or migrations that backfill data. These are the areas where mocks give the least assurance.
  • Feature developers. They write integration tests for the repositories and services they build, next to their unit tests.
  • Platform or developer-experience engineers. They own the shared harness: the container setup, migration runner, config loading, isolation strategy and standard provider overrides.
  • Teams whose CI can run containers. This can be through service containers or a job step that starts the database. Without that capability, the approach is hard to run consistently.

How does Test.createTestingModule work for unit and integration tests?

Test.createTestingModule() takes the same metadata as @Module() (imports, providers, controllers) and returns a builder. Calling .compile() runs Nest's dependency injection container and produces a TestingModule, from which you fetch instances with get(). Both unit and integration tests use this one entry point. The difference is how much of the real module graph you let it build.

Unit tests: declare the class, replace everything around it

A unit test lists only the provider under test in providers and supplies its dependencies as custom providers. Use useValue for a plain object of jest.fn() stubs. Use useFactory when the stub needs setup logic or other injected values. Because nothing is imported, the container never touches a database connection or config loader, so the test runs in milliseconds and fails only when the class's own logic is wrong. The developer building the feature writes these alongside the code, usually for services with branching business rules.

Integration tests: import the real graph, override only the edges

An integration test imports the actual feature module, along with the persistence module pointed at a test database. Before .compile(), it chains overrideProvider(Token).useValue(...) for dependencies that leave your process, such as outbound HTTP clients, queue producers, and email senders. Repositories, transactions, validation pipes and guards stay real. That is the reason to write these tests: they check that providers are wired correctly and that queries behave as you expect. Feature developers usually write them. Platform engineers typically own the shared harness that provisions the database and the standard overrides.

import { Test, TestingModule } from '@nestjs/testing';
import { OrdersService } from './orders.service';
import { OrdersModule } from './orders.module';
import { OrdersRepository } from './orders.repository';
import { PaymentsClient } from '../payments/payments.client';
import { MailService } from '../mail/mail.service';
import { TestDatabaseModule } from '../../test/test-database.module'; // shared harness, points at a test DB

// Unit: only the class under test is real; every dependency is a custom provider.
it('unit: rejects orders with no items', async () => {
  const moduleRef: TestingModule = await Test.createTestingModule({
    providers: [
      OrdersService,
      { provide: OrdersRepository, useValue: { save: jest.fn(), findById: jest.fn() } },
      // useFactory when the stub needs setup logic
      { provide: PaymentsClient, useFactory: () => ({ charge: jest.fn().mockResolvedValue({ status: 'ok' }) }) },
      { provide: MailService, useValue: { send: jest.fn() } },
    ],
  }).compile();

  const service = moduleRef.get(OrdersService);
  await expect(service.create({ customerId: 'cust_123', items: [] })).rejects.toThrow();
});

// Integration: real module graph and real DB; only process-external edges are swapped.
it('integration: persists an order', async () => {
  const moduleRef = await Test.createTestingModule({
    imports: [TestDatabaseModule, OrdersModule],
  })
    .overrideProvider(PaymentsClient) // outbound HTTP
    .useValue({ charge: jest.fn().mockResolvedValue({ status: 'ok' }) })
    .overrideProvider(MailService) // email
    .useValue({ send: jest.fn() })
    .compile();

  const service = moduleRef.get(OrdersService);
  const order = await service.create({ customerId: 'cust_123', items: [{ sku: 'SKU-1', qty: 2 }] });
  expect(await moduleRef.get(OrdersRepository).findById(order.id)).toBeDefined();
  await moduleRef.close();
});

The same Test.createTestingModule entry point used two ways: a unit test that supplies every dependency through useValue or useFactory, and an integration test that imports the real module graph and test database, then uses overrideProvider to replace only the HTTP and email edges.

Why do Jest mocks miss most bugs at the persistence boundary?

A Jest mock of a repository returns whatever you tell it to return. That makes it a record of what you believe the database does, not what it does. Most persistence bugs live in the gap between the two, and a mock cannot show you that gap.

Failures a mocked repository will never raise:

  • Constraint violations. A duplicate email that breaks a unique index, or an insert that references a missing parent row, succeeds against a mock.
  • Cascades. Deleting a parent may cascade, set children to null, or be rejected. That depends on the schema, not on your service code.
  • Transaction isolation. Two concurrent requests that read and then write the same row can lose an update. A mock runs each call in a vacuum.
  • Query builder mistakes. A wrong join, a misplaced WHERE clause, or a parameter bound to the wrong placeholder produces valid TypeScript and incorrect SQL.
  • Type coercion and nulls. Decimals returned as strings, timestamps shifted by time zone, and nullable columns that the entity declares as required.
  • Schema drift. The entity says a column exists. A migration renamed it last sprint.

Mock-heavy suites also fail in the opposite direction. Say someone changes a query so it silently drops soft-deleted rows. The test still passes, because the stubbed find returns the fixture it always returned. Now take a harmless refactor: replacing findOne with an equivalent query builder call. The behavior is identical, but tests break because they asserted which method was called. In the first case the suite missed a real change. In the second, engineers spend time rewriting tests over a change that altered nothing.

// users.service.spec.ts: a typical mock-heavy test that looks thorough but is not
import { Test } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { UsersService } from './users.service';
import { User } from './user.entity';

describe('UsersService (mocked repository)', () => {
  const repo = { findOne: jest.fn(), save: jest.fn() };
  let service: UsersService;

  beforeEach(async () => {
    jest.resetAllMocks();
    const moduleRef = await Test.createTestingModule({
      providers: [UsersService, { provide: getRepositoryToken(User), useValue: repo }],
    }).compile();
    service = moduleRef.get(UsersService);
  });

  it('creates a user', async () => {
    // Always succeeds: there is no unique index on email and no FK check,
    // so a duplicate or orphaned insert is never rejected here.
    repo.save.mockResolvedValue({ id: 1, email: 'ana@example.com' });
    await expect(service.create({ email: 'ana@example.com' })).resolves.toMatchObject({ id: 1 });
  });

  it('finds an active user by email', async () => {
    // The fixture comes back regardless of the query. If someone adds
    // withDeleted: true, soft-deleted rows leak into results and this still passes.
    repo.findOne.mockResolvedValue({ id: 1, email: 'ana@example.com' });
    await service.findActiveByEmail('ana@example.com');

    // Couples the test to the method name: replacing findOne with an
    // equivalent createQueryBuilder() call fails here with no behavior change.
    expect(repo.findOne).toHaveBeenCalledWith(
      expect.objectContaining({ where: expect.objectContaining({ email: 'ana@example.com' }) }),
    );
  });
});

A mocked TypeORM repository test that cannot raise constraint violations, still passes after a query change exposes soft-deleted rows, and breaks after a behavior-preserving switch from findOne to the query builder.

When should you mock, use a real database, or use a fake?

The way out is to choose the test double by what a layer does, not by habit. A layer that owns decisions gets mocks. A layer that owns SQL gets a real database. A layer that talks to systems you don't control gets a fake.

Layer Default Why Alternative
Controllers, services with branching logic Jest mocks of collaborators The branching logic is what you are testing, and a database only adds setup and runtime An HTTP-level integration test when a branch depends on persisted state
Repositories, custom queries, transactions, constraints Real database, same engine as production Behaviour lives in the engine: dialect, locking, isolation, unique and foreign-key enforcement None that tests the same thing
Migrations Real database, full migration chain from empty Ordering and data-backfill bugs only appear when migrations actually run Schema diff checks in CI as a supplement
Third-party HTTP, queues, email Stubs or in-process fakes at the adapter These systems are slow and nondeterministic, and you don't own them Contract tests against a provider sandbox, run separately

Swapping in SQLite or an in-memory store for a different production engine gives false confidence. The two engines differ in type coercion, case sensitivity in comparisons, JSON operators, upsert syntax and transaction isolation. A passing test proves only that the query works on the substitute engine.

Some code doesn't need integration tests at all. Pure mapping functions, DTO validation and thin services that only forward calls to a repository fall in this group. Unit-test the mapping and validation. For pass-through services, rely on the repository's integration tests rather than covering the same path twice.

When should you avoid real-database integration tests?

A real database is the wrong tool in these situations:

  • The code has no persistence behavior. Pure functions, mappers, DTO validation and branching business rules are better covered by unit tests. A database there adds setup, runtime and failure modes without adding coverage.
  • You need to enumerate many input permutations. Edge cases of a pricing rule or a state machine belong in fast unit tests. Keep integration tests to a few representative paths per query or transaction.
  • You need feedback on every file save. Integration suites need a running container and migrations. Keep them out of watch mode and run them before merge.
  • The dependency is a third-party system. Pointing tests at a real payment API, broker or auth server makes them slow and nondeterministic. Use fakes at the adapter, and cover those systems with separate contract tests.
  • You can't run the production engine in a container. Some managed services have no local equivalent. A different engine substituted in its place tests the wrong thing. Cover the persistence layer instead with tests against a dedicated non-production instance of the real service, and be explicit that the local suite does not cover it.
  • The service is a thin pass-through. If a service only forwards calls to a repository, the repository's integration tests already cover the path.

How do you provision a test database for NestJS integration testing?

Start with the engine. If production runs PostgreSQL, the tests run PostgreSQL, ideally the same major version, in a container. SQLite or an in-memory substitute handles constraints, locking, JSON columns, collation and transaction isolation differently. Those differences are the bugs you are trying to catch. Use the same container image locally (through a Compose file or a test-container library) and in CI (as a service container or a job step). A test that passes on a laptop then means the same thing in the pipeline.

Apply real migrations, not schema sync

Turn off ORM auto-sync options such as TypeORM's synchronize for tests. Instead, run your migration files against the empty container before the suite starts. Sync builds the schema from your entity definitions, so it hides a migration that is missing, out of order or wrong. Running migrations in every test run also tests the deployment path. A broken migration fails in CI instead of during a release.

Load config the way production does

Don't hard-code connection strings in test files. Import the same config module the application uses, such as ConfigModule with a test-specific env file. That way validation schemas, defaults and naming conventions apply in tests too. A misnamed variable then fails the test instead of failing at deploy time.

Budget for the container

Each CI job now pulls an image, starts the database and runs migrations before any test executes.

Illustrative estimate: suppose this costs 30 seconds and runs in 40 pipelines a day. That adds 20 minutes of runner time daily. You can reduce it by caching the image, starting one database per job rather than per test file, and keeping migrations lean.

// test/create-test-app.ts: builds a Nest app wired to the containerized test database
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { join } from 'path';
import { UsersModule } from '../src/users/users.module';

export async function createTestApp(): Promise<INestApplication> {
  const moduleRef = await Test.createTestingModule({
    imports: [
      // Same config module as production; only the env file differs.
      // .env.test points at the Postgres container, e.g. DB_HOST=localhost, DB_PORT=5432
      ConfigModule.forRoot({ isGlobal: true, envFilePath: '.env.test' }),
      TypeOrmModule.forRootAsync({
        inject: [ConfigService],
        useFactory: (config: ConfigService) => ({
          type: 'postgres',
          // getOrThrow makes a misnamed variable fail the test, not the deploy
          host: config.getOrThrow<string>('DB_HOST'),
          port: Number(config.getOrThrow<string>('DB_PORT')),
          username: config.getOrThrow<string>('DB_USER'),
          password: config.getOrThrow<string>('DB_PASSWORD'),
          database: config.getOrThrow<string>('DB_NAME'),
          autoLoadEntities: true,
          // Never build the schema from entities in tests: it hides broken migrations
          synchronize: false,
          // Apply the real migration files on startup, exercising the deploy path
          migrationsRun: true,
          migrations: [join(__dirname, '../src/migrations/*.{ts,js}')],
        }),
      }),
      UsersModule,
    ],
  }).compile();

  const app = moduleRef.createNestApplication();
  await app.init();
  return app;
}

A NestJS test helper that loads settings through the production ConfigModule with a test env file, connects to the containerized PostgreSQL, disables TypeORM synchronize, and runs the real migrations before the tests execute.

Which test isolation strategy should you choose?

Once the database is running, each test needs to start from a known state. There are three common ways to reset that state, and they fail in different ways.

Per-test transaction rollback opens a transaction in beforeEach, routes all queries through that connection, and rolls back in afterEach. Resetting costs almost nothing, but rollback only works if every query uses that one transaction. It breaks in three cases:

  • The code under test opens its own transaction. Depending on the ORM, this becomes a savepoint or a separate transaction, and data committed there escapes the rollback.
  • The code uses a second pooled connection. That connection cannot see the uncommitted rows.
  • The schema uses deferred constraints. These are checked at commit, and the test never commits, so violations pass silently.

Truncation lets tests commit normally and empties every table afterward. The code runs the same way it does in production. The reset gets slower as you add tables and foreign keys.

Schema or database per Jest worker fixes a separate problem. Jest runs test files in parallel workers. If those workers share one database, one worker can truncate tables while another is reading them, unique keys collide, and row counts depend on timing. The resulting failures often disappear on rerun. You can derive a schema name from JEST_WORKER_ID and run migrations once per schema. Then use truncation or rollback inside each worker.

Strategy Setup complexity Per-test reset time Breaks when
Transaction rollback Medium: requires connection plumbing Near zero Code opens its own transactions, uses multiple connections, or relies on deferred constraints
Truncation Low Grows with table count Workers share a database
Schema per worker High: per-worker migrations Depends on the reset used inside each worker Migrations are slow or the database caps connections
// test/db.ts: one Postgres schema per Jest worker, truncated between tests
import { Pool } from 'pg';

// Jest sets JEST_WORKER_ID to '1', '2', ... for each parallel worker
const workerId = process.env.JEST_WORKER_ID ?? '1';
export const schema = `test_w${workerId}`;

export const pool = new Pool({
  connectionString: 'postgres://app:app_password@localhost:5432/app_test',
});

// Every pooled connection must point at this worker's schema,
// or a second connection would read another worker's tables
pool.on('connect', (client) => {
  client.query(`SET search_path TO ${schema}`);
});

export async function setupSchema(runMigrations: (p: Pool) => Promise<void>) {
  // Run once per worker (e.g. in beforeAll), not once per test
  await pool.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`);
  await pool.query(`CREATE SCHEMA ${schema}`);
  await runMigrations(pool);
}

export async function truncateAll() {
  // Tests commit normally; empty only this worker's tables afterward
  const { rows } = await pool.query(
    `SELECT tablename FROM pg_tables WHERE schemaname = $1`,
    [schema],
  );
  if (rows.length === 0) return;
  const tables = rows.map((r) => `"${schema}"."${r.tablename}"`).join(', ');
  // One statement for all tables; CASCADE handles foreign keys
  await pool.query(`TRUNCATE ${tables} RESTART IDENTITY CASCADE`);
}

// In a spec: beforeAll(() => setupSchema(migrate));
//            afterEach(truncateAll);  afterAll(() => pool.end());

This example gives each Jest worker its own Postgres schema, named from JEST_WORKER_ID, and truncates only that schema's tables after each test, so parallel workers never touch each other's data.

How do you keep integration tests fast, readable and free of flakiness?

Lifecycle hygiene

Build the Nest application once per test file in beforeAll, reset state in beforeEach, and call app.close() in afterAll. Compiling the module graph and opening a connection pool are the slow steps, so do them once per file. Resetting data before each test keeps tests independent of execution order. app.close() runs shutdown hooks and lets ORM integrations close their pools. Skip it and Jest either hangs after the run or prints a warning that it did not exit. To find the cause, run with --detectOpenHandles. The usual culprits are database pools, queue or cache clients, and timers started in onModuleInit.

Leaks make tests flaky in ways that are hard to trace. A pool that is never closed can exhaust the database's connection limit, so a later file fails while connecting. A run that crashes partway through leaves rows behind. Reset at the start of each test, not only at the end, so a crashed run cannot break the next one.

Data builders over fixture files

Shared fixture files become hidden dependencies. One test edits a row, and an unrelated test breaks. Use builders or factory functions that create only the records a test needs, with defaults you can override. The test then states its own preconditions.

Controlling the module graph

Importing AppModule pulls in every provider. A mail client or other external dependency that fails during initialization will fail tests that never use it. Import only the feature modules under test. Replace external dependencies with overrideProvider, and keep the real database connection. A smaller graph also starts faster.

How should you organize unit and integration suites to control cost?

Split the suites at the configuration level, not just by folder. Use either two Jest config files or a single config with projects. Give each suite its own testMatch pattern, such as *.spec.ts for unit tests and *.int-spec.ts for integration tests. Global setup, database provisioning and longer timeouts then apply only to the integration project, and a unit run never waits for a container to start.

Run unit tests on every save and every push, because they finish in seconds and need no infrastructure. Run integration tests as a required check before merge. That is where a broken migration or query costs the least to fix.

Type every mock against the real provider class or interface, for example with jest.Mocked<UsersRepository>. When a method signature changes, the compiler then flags the stale mock. Assert on returned values, thrown exceptions and persisted state rather than on toHaveBeenCalledTimes sequences. Call-order assertions break on harmless refactors and still pass when the behavior is wrong.

Data-layer integration tests prove your code works with your database. They prove nothing about a payment API, message broker or third-party auth server, because those stay overridden. Cover external services with contract tests or a small end-to-end suite.

Illustrative estimate (assumed numbers, not a benchmark).

Use this formula:

net hours saved per month = (bugs caught per month × hours to fix each in production) − (hours to build ÷ amortization months + monthly maintenance hours)

Assumed inputs:

  • 2 persistence bugs caught per month
  • 6 hours to fix each one in production
  • 30 hours to build the suite, amortized over 12 months
  • 3 hours of maintenance per month

Plugging these in: (2 × 6) − (30 ÷ 12 + 3) = 12 − 5.5 = 6.5 hours saved per month. Replace the assumed inputs with your own figures to check whether the suite pays for itself.

How can this approach save engineering time?

The time savings come from finding failures earlier and from spending less time maintaining tests:

  • Persistence bugs surface before merge. Constraint violations, wrong joins, coercion surprises and broken migrations fail in CI. Otherwise they show up in production, where fixing them can also mean diagnosing the incident, repairing data and coordinating a hotfix.
  • Migrations are tested on every run. Running the real migration chain from an empty database means a release is less likely to stall on a migration that never ran outside a developer's machine.
  • Refactors break fewer tests. Tests that assert on returned values and persisted state, not on which repository method was called, survive behavior-preserving changes such as moving from findOne to the query builder. Engineers stop rewriting tests that were never wrong about behavior.
  • Fewer flaky reruns. Per-worker schemas, resetting state at the start of each test, and closing the app properly all remove the intermittent failures that cost time to investigate and rerun.
  • One harness serves every team. A shared helper that provisions the database, loads config and applies standard overrides means each feature team writes only the test bodies, not their own setup.
  • Unit tests stay fast. Keeping branching logic in mocked unit tests and running integration tests as a separate project preserves a seconds-long feedback loop during development.

Use the formula in the previous section with your own bug history and maintenance figures to check whether these savings outweigh the cost of building and running the suite.

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 integration 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 .env by 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.