0
0
NestJSframework~5 mins

E2E testing with supertest in NestJS

Choose your learning style9 modes available
Introduction

E2E testing checks if your whole app works well from start to finish. Supertest helps you test your NestJS app by simulating real HTTP requests.

You want to make sure your API routes respond correctly.
You want to test how different parts of your app work together.
You want to catch bugs before users see them.
You want to automate testing for your backend endpoints.
Syntax
NestJS
import request from 'supertest';
import { INestApplication } from '@nestjs/common';

// inside your test block
await request(app.getHttpServer())
  .get('/your-route')
  .expect(200)
  .expect('Content-Type', /json/);

Use app.getHttpServer() to get the server instance from your NestJS app.

Chain .expect() to check status codes and response headers or body.

Examples
Test a GET request to '/users' expecting a 200 OK status.
NestJS
await request(app.getHttpServer())
  .get('/users')
  .expect(200);
Test a POST request with data and check if the response contains a token.
NestJS
await request(app.getHttpServer())
  .post('/auth/login')
  .send({ username: 'test', password: '1234' })
  .expect(201)
  .expect(res => {
    if (!('token' in res.body)) throw new Error('Missing token');
  });
Sample Program

This is a simple E2E test for a NestJS app. It starts the app, sends a GET request to the root route, and expects a 200 status with 'Hello World!' text. Finally, it closes the app.

NestJS
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';

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

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

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

  it('/ (GET)', () => {
    return request(app.getHttpServer())
      .get('/')
      .expect(200)
      .expect('Hello World!');
  });

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

Always call await app.init() before sending requests.

Close the app with await app.close() to free resources.

Use .send() to add data for POST or PUT requests.

Summary

E2E testing checks your app as a whole using real HTTP calls.

Supertest works well with NestJS to simulate these calls.

Write tests that start the app, send requests, check responses, and close the app.