0
0
NestJSframework~8 mins

E2E testing with supertest in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: E2E testing with supertest
MEDIUM IMPACT
This affects the speed and resource usage of automated end-to-end tests, impacting test suite run time and developer feedback loops.
Running E2E tests for API endpoints in NestJS using Supertest
NestJS
beforeAll(async () => {
  const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
  app = moduleRef.createNestApplication();
  await app.init();
});

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

test('GET /users returns 200', async () => {
  await request(app.getHttpServer()).get('/users').expect(200);
});
Starting the app once before all tests and closing it after reduces server startup overhead and speeds up the entire test suite.
📈 Performance GainReduces server startups from N times to 1, cutting test suite runtime significantly
Running E2E tests for API endpoints in NestJS using Supertest
NestJS
beforeEach(async () => {
  const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
  app = moduleRef.createNestApplication();
  await app.init();
});

test('GET /users returns 200', async () => {
  await request(app.getHttpServer()).get('/users').expect(200);
});
Starting a new NestJS app instance before each test causes repeated server startups, increasing total test time and CPU usage.
📉 Performance CostBlocks test execution for multiple seconds per test due to repeated app initialization
Performance Comparison
PatternServer StartupsNetwork RequestsTest Suite RuntimeVerdict
Start app before each testN timesN requestsHigh (slow)[X] Bad
Start app once before all tests1 timeN requestsLow (fast)[OK] Good
Rendering Pipeline
E2E tests with Supertest do not affect browser rendering but impact Node.js server startup and network request handling during tests.
Server Initialization
Network Request Handling
Test Execution
⚠️ BottleneckServer Initialization (starting NestJS app instance)
Optimization Tips
1Reuse the NestJS app instance across multiple tests to avoid repeated startups.
2Close the app instance after all tests to free resources.
3Avoid starting the server before each individual test to reduce total runtime.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance issue when starting a NestJS app before each E2E test?
ANetwork requests become slower
BTests fail due to app state sharing
CRepeated server startups increase total test runtime
DBrowser rendering is blocked
DevTools: Node.js Profiler or Jest --runInBand with --detectOpenHandles
How to check: Run tests with profiling enabled or in single-thread mode to measure server startup time and open handles.
What to look for: Look for repeated server initialization logs and long delays before tests start running.