Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 42 ยท Testing and Production

Testing Nest Applications

Learn to test NestJS apps: Test.createTestingModule, overriding providers, unit tests with mocks, e2e tests with supertest, and test databases.

Nest was designed so that code is easy to test. Because every class receives its dependencies through the constructor, a test can hand a class a fake collaborator and check how it behaves, with no database, no network and no running server. The @nestjs/testing package adds one more tool on top: a testing module, a small copy of your module graph that you can build in a test and change on purpose.

This lesson covers the two kinds of tests you will write most: unit tests (one class, collaborators faked) and end-to-end tests (the real HTTP pipeline, usually with a fake or throwaway database). The Nest and Jest code is read-only because it needs Node and npm. The runnable examples build a tiny testing module by hand and run real node:test tests against it, so you see exactly what createTestingModule, overrideProvider and get do.

Two kinds of tests

Unit One class, fake dependencies, very fast.
End to end Real routes, pipes, guards and filters.
Database A throwaway database or a fake repository.

Many unit tests, fewer e2e tests, a handful of full-stack checks.

1 / 2

A unit test with a testing module

Suppose CatsService depends on a CatsRepository. In a unit test you do not want a real repository, so you register a fake under the same token:

TypeScript
import { Test } from '@nestjs/testing';
import { NotFoundException } from '@nestjs/common';

describe('CatsService', () => {
  let service: CatsService;
  const repository = {
    findById: jest.fn(),
  };

  beforeEach(async () => {
    const moduleRef = await Test.createTestingModule({
      providers: [
        CatsService,
        { provide: CatsRepository, useValue: repository },
      ],
    }).compile();

    service = moduleRef.get(CatsService);
    jest.resetAllMocks();
  });

  it('returns a cat that exists', async () => {
    repository.findById.mockResolvedValue({ id: 1, name: 'Mia' });
    await expect(service.findOne(1)).resolves.toEqual({ id: 1, name: 'Mia' });
  });

  it('throws NotFoundException for a missing cat', async () => {
    repository.findById.mockResolvedValue(null);
    await expect(service.findOne(2)).rejects.toThrow(NotFoundException);
  });
});

Three things are worth noticing. The testing module lists only what this test needs: the service and a fake for its one dependency. The fake is a plain object with jest.fn() methods, using a custom provider with useValue. And compile() returns a TestingModule, from which get() retrieves the instance.

A generated Nest project uses Jest by default. Nothing about the testing module is Jest-specific, though: any runner, including node:test or Vitest, can create modules and call get().

Overriding providers

When you test with a module that imports other modules, you may not control the providers inside them. overrideProvider replaces one by token after the module metadata is declared:

TypeScript
const moduleRef = await Test.createTestingModule({
  imports: [CatsModule],
})
  .overrideProvider(CatsRepository)
  .useValue(fakeRepository)
  .compile();

The same builder offers useClass and useFactory, plus overrideGuard, overridePipe, overrideInterceptor and overrideFilter for the parts of the request pipeline. A common use is overrideGuard(AuthGuard).useValue({ canActivate: () => true }) so a test of a controller does not need real tokens.

If a class has many dependencies and you only care about one, useMocker lets you supply a factory that builds an automatic mock for every token that was not registered. That saves a long list of fakes, but be careful: a mock that answers undefined to everything can hide a missing setup.

Two details matter for scoped providers. A REQUEST or TRANSIENT provider (see Dynamic Modules and Provider Scopes) cannot be fetched with get(); use await moduleRef.resolve(Token) instead.

End-to-end tests

A unit test never touches routing. An e2e test creates the real application, with its controllers, pipes, guards and filters, and sends HTTP requests to it. The usual helper is supertest, which can talk to a server without opening a real port:

TypeScript
import { Test } from '@nestjs/testing';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import * as request from 'supertest';

describe('Cats (e2e)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({
      imports: [AppModule],
    })
      .overrideProvider(CatsRepository)
      .useValue(new InMemoryCatsRepository())
      .compile();

    app = moduleRef.createNestApplication();
    app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
    await app.init();
  });

  afterAll(async () => {
    await app.close();
  });

  it('POST /cats creates a cat', async () => {
    const res = await request(app.getHttpServer())
      .post('/cats')
      .send({ name: 'Mia' })
      .expect(201);
    expect(res.body).toMatchObject({ name: 'Mia' });
  });

  it('POST /cats rejects an invalid body', () => {
    return request(app.getHttpServer()).post('/cats').send({}).expect(400);
  });
});

An important trap: global pieces set in main.ts do not exist in a test. Calls like app.useGlobalPipes(...) live in the bootstrap function, so your test must repeat them (or, better, register them as providers with APP_PIPE and APP_FILTER, so the module itself carries them). If a validation test passes in production but the e2e test returns 201 for bad data, this is almost always why.

Always close the app in afterAll. A server or a database connection left open keeps the test process alive and slows the whole suite.

Test databases

Three approaches are common, from fast to faithful:

Approach Speed Faithfulness
Fake repository (in-memory class) Very fast Low: it does not behave like SQL
SQLite in memory Fast Medium: SQL dialects differ from production
A real database in a container Slower High: same engine, same constraints

Whatever you choose, tests must not depend on each other. Reset state between tests by truncating tables, by wrapping each test in a transaction that is rolled back, or by creating a fresh schema per test file. The fake repository is the simplest, and it is also the right choice for most unit tests. Keep a smaller set of tests that run against the real engine, because constraints, unique indexes and transaction behavior are exactly what a fake cannot prove. Migrations belong in that setup too: run them before the suite so the test schema matches production (see Transactions and Migrations).

Stand-in: a hand-written testing module

The code below is not @nestjs/testing. It is a short imitation: createTestingModule collects providers, overrideProvider records replacements, compile builds instances (constructor dependencies listed in a static inject array), and get returns one. The tests are real node:test tests, run through the programmatic run() API so the output has no timings.

Node.js Unit tests with a hand-written testing module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The real CatsRepository throws, so the first two tests only pass because the override replaced it before compile() built the service. The third test shows the failure you see when a dependency is neither registered nor overridden. In Nest the message names the missing provider and the class that needs it, which is usually the quickest way to find a forgotten providers entry.

Stand-in: an end-to-end style request

An e2e test sends a request through everything that sits in front of the handler. This second stand-in runs a request through a validation step, a handler and an error mapper, and asserts on status codes and bodies the way a supertest test would. It also demonstrates why the test must repeat the global setup from main.ts.

Node.js End-to-end style tests: status codes and bodies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The third test is the trap in miniature: with validation switched off, the same request that should fail returns 201. In a real e2e test the equivalent mistake is forgetting app.useGlobalPipes(...) after createNestApplication().

Practical advice

  • Test behavior, not wiring. Assert on return values, thrown exceptions and status codes. Asserting that a particular method was called three times breaks every time you refactor.
  • Keep fakes honest. A fake repository that never returns null makes your "not found" branch untestable.
  • Test guards and pipes directly when they hold real logic. A guard is a class with one method, so new RolesGuard(reflector).canActivate(fakeContext) is a perfectly good unit test.
  • Run e2e tests serially if they share a database, and unit tests in parallel for speed.
  • Do not mock what you do not own too deeply. Mocking every call of an ORM proves little. Use a real database for the queries that matter.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Test.createTestingModule({...}).compile() give you?

    compile() builds the module graph and returns a TestingModule. You call get() (or resolve() for scoped providers) to retrieve instances. The HTTP application comes later from createNestApplication().
  2. 2. An e2e test returns 201 for an invalid body, although production returns 400. What is the most likely cause?

    Global pipes, filters and interceptors added with app.useGlobal... in main.ts are not part of the module. Repeat them in the test, or register them with APP_PIPE-style providers.
  3. 3. Which call replaces a provider with a fake after the module is declared?

    overrideProvider on the testing module builder swaps the provider registered under that token before compile(). useClass and useFactory work the same way.
  4. 4. Why should you keep some tests running against a real database engine?

    An in-memory fake only does what you wrote it to do. Real SQL constraints and transactions can only be verified against the real engine (or a close match in a container).
  5. 5. Why do you call app.close() in afterAll?

    An open server or connection keeps the process alive and may leak between test files. Closing the app also runs the shutdown lifecycle hooks.

Summary

  • Test.createTestingModule() builds a small module graph for a test; compile() returns a module and get() retrieves providers (resolve() for scoped ones).
  • Unit tests fake the collaborators with useValue, or with overrideProvider when a provider comes from an imported module.
  • e2e tests use createNestApplication() and supertest; repeat global pipes and filters from main.ts, or register them as providers, and always call app.close().
  • Choose a test database by trade-off: fake repository, in-memory SQLite, or a real engine in a container, and keep tests independent of each other.
  • Test behavior (results, errors, status codes), not internal calls.

Continue with Security and Hardening to protect the API you just learned to test.