skip to content

In a NestJS e2e test, what do createNestApplication(), app.init(), getHttpServer() and app.close() each contribute to a Supertest request?

level: middleimportance: must knowfreq 58%

answer

  1. an app over the compiled graph
  2. routes appear only after a step
  3. hand Supertest the raw server
  4. main.ts never runs

basics

~20 s

createNestApplication() wraps the compiled TestingModule in an INestApplication on the Express adapter; app.init() registers middleware and routes and runs init hooks; getHttpServer() gives Supertest the Node server; app.close() runs shutdown hooks and closes the server.

solid answer

~40 s

After `compile()`, `moduleRef.createNestApplication()` creates an `INestApplication` over the same container, using the Express adapter from `@nestjs/platform-express` unless you pass another adapter. It is not ready yet: `await app.init()` registers middleware, routes and the not-found and exception handlers, and calls `onModuleInit` and `onApplicationBootstrap`. Skip it and every Supertest call gets a 404. `request(app.getHttpServer())` passes Supertest the underlying Node HTTP server; Supertest binds it to an ephemeral port itself, so no `listen()` is needed. In `afterAll`, `await app.close()` runs the destroy and shutdown hooks and closes the server so the runner can exit. One trap: `main.ts` never runs in the test, so `useGlobalPipes()`, `setGlobalPrefix()` and similar calls made there are missing unless the test applies them too.

code

typescript · 27 lines
typescript
import request from 'supertest';
import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { OrdersModule } from '../src/orders/orders.module.js';
import { OrdersRepository } from '../src/orders/orders.repository.js';

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

  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({ imports: [OrdersModule] })
      .overrideProvider(OrdersRepository)
      .useValue({ findAll: async () => [] })
      .compile();

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

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

  it('GET /orders answers 200 with an empty list', () => {
    return request(app.getHttpServer()).get('/orders').expect(200).expect([]);
  });
});

go deeper

for a junior

Recall the sequence in order: compile the module, call createNestApplication, await app.init(), send requests through request(app.getHttpServer()), and await app.close() in afterAll.

for a middle

Explain what init() registers and which hooks it calls, why Supertest needs the raw server, and what close() tears down.

for a senior

Diagnose e2e results that differ from production because main.ts configuration was never applied, and fix it with APP_* tokens or shared setup.

for a principal

Decide how a team keeps test and production bootstrapping identical, so e2e suites cannot drift from what actually ships.

## From a compiled module to a running app An **end-to-end (e2e) test** in NestJS sends real HTTP requests through routing, middleware, guards, pipes, interceptors and filters. It starts like a unit test, with `Test.createTestingModule({ imports: [OrdersModule] })` and `compile()`, often with `overrideProvider()` calls that swap a data-access class for a fake. The compiled `TestingModule` holds instances but serves nothing; four calls turn it into something Supertest can talk to. ## The four calls 1. **`moduleRef.createNestApplication()`** creates an `INestApplication` over the compiled container. With no arguments it uses the Express adapter from `@nestjs/platform-express`; you can pass another adapter, such as a Fastify one, as the first argument. 2. **`await app.init()`** does the work that `app.listen()` would do before opening a port: it registers middleware and the router, calls `onModuleInit` hooks, registers the not-found and exception handlers, and calls `onApplicationBootstrap` hooks. The docs state you must call it manually. 3. **`app.getHttpServer()`** returns the Node HTTP server the adapter created. Passing it to Supertest as `request(app.getHttpServer())` lets Supertest bind it to an ephemeral port on its own when it is not listening, so the test never manages ports. 4. **`await app.close()`** runs the shutdown sequence: it calls `onModuleDestroy` and `beforeApplicationShutdown` hooks, closes the adapter's server, then calls `onApplicationShutdown` hooks. ## What goes wrong when one is skipped | Skipped call | Symptom | |---|---| | `app.init()` | every request returns 404: no Nest routes were registered on the server | | `app.close()` | the server and any connections opened by providers stay open, which can keep the test process from exiting | | `afterAll` without `await` on `close()` | teardown hooks may still be running when the runner moves on | ## The main.ts gap `main.ts` builds the production app with `NestFactory.create(AppModule)` and then configures **that instance**: `app.useGlobalPipes(new ValidationPipe(...))`, `app.setGlobalPrefix('api')`, `app.enableVersioning(...)`, `app.enableCors()`. An e2e test never executes `main.ts`; it creates a different instance from the testing module. Anything configured on the instance is therefore **absent** in the test: - a request with an invalid body can reach the handler because no global validation pipe runs; - routes answer at `/orders` instead of `/api/orders`; - versioned routes do not resolve as they do in production. Two remedies are common: - **Move global enhancers into a module** using the `APP_PIPE`, `APP_GUARD`, `APP_INTERCEPTOR` and `APP_FILTER` tokens. Those are part of the module graph, so the testing module picks them up during `compile()`. - **Extract a shared setup function** (for example `configureApp(app)`) that `main.ts` and every e2e suite call before `init()`, so both instances get identical prefix, versioning and pipes. ## Fastify instead of Express With a Fastify adapter the docs add one step: after `await app.init()`, call `await app.getHttpAdapter().getInstance().ready()`. Fastify can then answer injected requests with `app.inject({ method: 'GET', url: '/orders' })`, which needs no Supertest at all. ## Overrides and adapters in the same suite Everything from the unit-testing side still applies before `createNestApplication()`: `overrideProvider`, `overrideGuard`, `overrideModule` and `useMocker` all act during `compile()`, so the application you create already contains the stand-ins. Two consequences are easy to miss: - An override recorded after `compile()` has no effect on an application created from that module. - Code that reads `HttpAdapterHost` finds its `httpAdapter` still undefined when the test stops at `compile()`; the docs recommend creating the application with `createNestApplication()` in that case, or refactoring the dependency. When a suite needs a different set of overrides, compile a separate testing module for it rather than trying to change the one already running. ## A typical lifecycle per suite - `beforeAll`: compile the module with overrides, create the app, apply shared setup, `await app.init()`. - each test: `request(app.getHttpServer()).get('/orders').expect(200)`. - `afterAll`: `await app.close()`. Creating the app once per suite rather than per test keeps the cost of scanning and instantiating the graph down, at the price of tests sharing the same instances.

  • A NestJS e2e test accepts an invalid order body that production rejects with 400. What is the likely cause?
    Production registers `ValidationPipe` with `app.useGlobalPipes()` in `main.ts`, and the e2e test never runs `main.ts`, so its app instance has no global pipe. Either register the pipe as an `APP_PIPE` provider in a module, which the testing module compiles in, or call a shared setup function on the test app before `init()`.
  • When a NestJS test only needs a provider from the graph, why skip createNestApplication() entirely?
    A compiled `TestingModule` already holds every static instance, so `moduleRef.get()` is enough for service-level tests. Creating an application adds the HTTP adapter, route registration and init hooks. One case that does need it is code that reads `HttpAdapterHost`: the docs note its `httpAdapter` is still undefined after `compile()` alone.

  • createNestApplication() returns an app that is ready for requests
  • The e2e app must call listen() on a fixed port for Supertest
  • Global pipes from main.ts apply automatically in e2e tests
  • app.close() is optional because the runner exits anyway
  • createNestApplication() always needs an adapter argument