0
0
NestJSframework~30 mins

E2E testing with supertest in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
E2E Testing with Supertest in NestJS
📖 Scenario: You are building a simple NestJS application that manages a list of books. You want to ensure your API endpoints work correctly by writing end-to-end (E2E) tests using supertest. This will help catch bugs early and keep your app reliable.
🎯 Goal: Write E2E tests for the GET /books endpoint using supertest in a NestJS testing environment. You will set up the test module, configure the app, write the test to check the response, and finalize the test suite.
📋 What You'll Learn
Create a NestJS testing module with the BooksModule
Initialize the NestJS application for testing
Write a supertest test to check the GET /books endpoint returns status 200 and an empty array
Close the NestJS application after tests complete
💡 Why This Matters
🌍 Real World
E2E testing ensures your API works as expected from the user's perspective. It helps catch bugs before deployment and improves software quality.
💼 Career
Many companies require developers to write automated tests for backend APIs. Knowing how to write E2E tests with NestJS and supertest is a valuable skill for backend and full-stack roles.
Progress0 / 4 steps
1
Setup NestJS Testing Module
Import Test and TestingModule from @nestjs/testing. Create a testing module with BooksModule using Test.createTestingModule and compile it. Assign the compiled module to a variable called moduleFixture.
NestJS
Need a hint?

Use Test.createTestingModule with imports: [BooksModule] and call compile() to get the testing module.

2
Initialize NestJS Application for Testing
Create a NestJS application instance from moduleFixture by calling createNestApplication(). Assign it to a variable called app. Then call await app.init() to initialize the app.
NestJS
Need a hint?

Use moduleFixture.createNestApplication() to create the app, then call await app.init().

3
Write E2E Test for GET /books Endpoint
Use supertest to send a GET request to /books on the app.getHttpServer(). Write a test that expects the response status to be 200 and the response body to be an empty array []. Use await request(app.getHttpServer()).get('/books').expect(200).expect([]).
NestJS
Need a hint?

Use request(app.getHttpServer()).get('/books').expect(200).expect([]) to test the endpoint.

4
Close the NestJS Application After Tests
Call await app.close() to properly shut down the NestJS application after tests finish.
NestJS
Need a hint?

Call await app.close() to clean up the app after tests.