NestJS E2E Testing
E2E tests verify the real HTTP pipeline: pipes, guards, interceptors, and controllers together. This lesson uses Nest's testing module with Supertest.
Bootstrapping an E2E App Create a TestingModule from AppModule (or a feature-focused module), compile it, create a Nest application, initialize it, then use Supertest against app.getHttpServer().
const moduleFixture = await Test.createTestingModule({ imports: [AppModule] })
.overrideProvider(UsersService)
.useValue(mockUsersService)
.compile();
app = moduleFixture.createNestApplication();
await app.init();
await request(app.getHttpServer()).get('/users').expect(200); Overrides keep e2e tests from requiring a real database while still exercising HTTP wiring.
Lifecycle Cleanup afterEach(async () => {
await app.close();
}); Apply the same global pipes/filters in e2e setup that production main.ts applies. Use .expect(status).expect(body) fluent assertions from Supertest. Seed or mock auth for protected routes explicitly. Prefer dedicated test database when true persistence is required. E2E Testing Cheatsheet Pieces of a Nest e2e spec.
Step API Build module Test.createTestingModule Override deps .overrideProvider().useValue() Create app createNestApplication() Init await app.init() HTTP assert request(server).get(...).expect(...) Cleanup await app.close()
Parity With main.ts If main.ts sets a global ValidationPipe, e2e tests should set it too—otherwise validation behavior differs between tests and production.
Authenticated Requests Generate a test JWT or override AuthGuard for endpoint authorization tests. Cover both 401 and happy-path authorized cases.
Common Mistakes Forgetting app.close() and leaking sockets/handles. Not applying global pipes used in production. Making every e2e hit a real third-party API. Gigantic e2e suites that take minutes and get skipped. Key Takeaways E2E tests boot Nest and assert HTTP behavior with Supertest. Override providers to avoid flaky external dependencies. Mirror global setup from main.ts. Always close the app after tests.
Pro Tip
Keep a thin set of smoke e2e tests for critical routes on every PR, and reserve broader e2e coverage for nightly CI if runtime becomes a bottleneck.
NestJS Unit Testing Go to next item