Skip to the content

Lesson 211 of 296

Testing NestJS applications

What you will learn

  • The Nest testing module
  • Unit testing a service with mocked dependencies
  • Overriding providers
  • Testing guards and pipes
  • End-to-end tests with Supertest
  • Testing with a real database
On this page

The testing module

@nestjs/testing builds a small Nest application for a test, with the same DI container as the real app. You choose which real providers to include and which to replace:

TypeScript
import { Test } from "@nestjs/testing";
import { describe, it, expect, beforeEach } from "vitest";

describe("CheckoutService", () => {
  let service: CheckoutService;
  const charges: Array<{ amountPence: number; customerId: string }> = [];

  beforeEach(async () => {
    charges.length = 0;
    const moduleRef = await Test.createTestingModule({
      providers: [
        CheckoutService,
        {
          provide: PAYMENT_GATEWAY,
          useValue: {
            charge: async (amountPence: number, customerId: string) => {
              charges.push({ amountPence, customerId });
              return { id: "ch_test" };
            }
          }
        }
      ]
    }).compile();

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

  it("charges the gateway with the amount and customer", async () => {
    await expect(service.pay("cus_1", 2500)).resolves.toEqual({ id: "ch_test" });
    expect(charges).toEqual([{ amountPence: 2500, customerId: "cus_1" }]);
  });
});
  • Test.createTestingModule({...}).compile() resolves the dependency graph, just like the real app.
  • useValue replaces the payment gateway with a fake, because CheckoutService depends on the token, not a concrete class (Lesson 208).
  • moduleRef.get(CheckoutService) returns the instance Nest built.

Overriding providers in a full module

To load a real module but replace one dependency:

const moduleRef = await Test.createTestingModule({ imports: [CheckoutModule] })
  .overrideProvider(PAYMENT_GATEWAY)
  .useValue(fakeGateway)
  .compile();

Similarly overrideGuard(AuthGuard).useValue({ canActivate: () => true }) skips authentication in tests that are about something else (keep separate tests that check the guard itself).

Unit testing guards and pipes

Guards and pipes are plain classes; test them directly with a fake ExecutionContext, or (often simpler and closer to reality) through an HTTP test as below.

End-to-end tests with Supertest

Create the whole application in memory and send real HTTP requests (Lesson 206):

TypeScript
import { Test } from "@nestjs/testing";
import { Module, StandardSchemaValidationPipe, type INestApplication } from "@nestjs/common";
import request from "supertest";
import { afterAll, beforeAll, describe, expect, it } from "vitest";

@Module({ controllers: [AdminController, ProductsController], providers: [RolesGuard] })
class TestAppModule {}

describe("HTTP pipeline (e2e)", () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({ imports: [TestAppModule] }).compile();
    app = moduleRef.createNestApplication();
    app.useGlobalPipes(new StandardSchemaValidationPipe());
    app.useGlobalFilters(new ProblemDetailsFilter());
    await app.init();
  });

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

  it("returns 401 without a token", async () => {
    await request(app.getHttpServer()).get("/admin/stats").expect(401);
  });

  it("returns 403 for a user without the admin role", async () => {
    await request(app.getHttpServer()).get("/admin/stats").set("Authorization", "Bearer staff-token").expect(403);
  });

  it("wraps successful responses and adds timing", async () => {
    const res = await request(app.getHttpServer())
      .get("/admin/stats")
      .set("Authorization", "Bearer admin-token")
      .expect(200);
    expect(res.body).toEqual({ data: { requestedBy: "u1", orders: 42 } });
    expect(res.headers["server-timing"]).toMatch(/^app;dur=/);
  });

  it("validates the body with the Zod schema", async () => {
    await request(app.getHttpServer()).post("/products").send({ name: "Mug", pricePence: -1 }).expect(400);
    await request(app.getHttpServer()).post("/products").send({ name: "Mug", pricePence: 499, role: "admin" }).expect(400);
    const ok = await request(app.getHttpServer()).post("/products").send({ name: " Mug ", pricePence: 499 }).expect(201);
    expect(ok.body).toEqual({ created: { name: "Mug", pricePence: 499, tags: [] } });
  });

  it("coerces route parameters", async () => {
    const res = await request(app.getHttpServer()).get("/products/7").expect(200);
    expect(res.body).toEqual({ id: 7, typeOfId: "number" });
  });
});
  • createNestApplication() + app.init() builds the app without listening on a port; app.getHttpServer() gives Supertest the server.
  • Register the same global pipes, filters and settings as main.ts. A good practice: put them in a shared configureApp(app) function used by both, so tests match production.
  • app.close() runs shutdown hooks and frees resources.

A real database

For repository and integration tests, use a real database in a container (Testcontainers, Lesson 206), run migrations once, and isolate tests with transactions or by truncating tables. Override only external services (payments, email) with fakes.

What to test in a NestJS app

  • Services: business rules and error cases (unit tests with fakes).
  • Guards: 401 and 403 paths, roles metadata.
  • Validation: invalid bodies, unknown fields, type coercion.
  • Error format: filters produce the agreed shape without leaking internals.
  • Authorisation: users cannot access other users' or tenants' data (Lesson 203).

How to say it in an interview

"I use the Nest testing module, which builds a real DI container for the test. For unit tests I include the service and replace its dependencies with useValue fakes, which is easy when the service depends on tokens or abstractions. With full modules I use overrideProvider and overrideGuard. For end-to-end tests I create the Nest application in memory, apply the same global pipes and filters as main.ts through a shared setup function, and send real requests with Supertest, covering 401, 403, validation errors and success paths, closing the app afterwards. Repositories are tested against a real database in a container."

Key words

WordMeaning
Test.createTestingModuleBuilds a Nest DI container for a test
overrideProviderReplaces a provider in a test module
overrideGuardReplaces a guard in a test module
createNestApplicationCreates the full app for e2e tests
getHttpServerThe underlying server Supertest calls

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.