Performance: E2E testing with supertest
This affects the speed and resource usage of automated end-to-end tests, impacting test suite run time and developer feedback loops.
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); });
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); });
| Pattern | Server Startups | Network Requests | Test Suite Runtime | Verdict |
|---|---|---|---|---|
| Start app before each test | N times | N requests | High (slow) | [X] Bad |
| Start app once before all tests | 1 time | N requests | Low (fast) | [OK] Good |
supertest in NestJS E2E testing?supertest in a NestJS E2E test file?import * as request from 'supertest'; is the correct syntax to import all exports as an object.const app = await NestFactory.create(AppModule);
await app.init();
return request(app.getHttpServer())
.get('/users')
.expect(200);
const app = await NestFactory.create(AppModule);
return request(app.getHttpServer())
.post('/login')
.send({ username: 'user', password: 'pass' })
.expect(201);
await app.close();return statement ends the function immediately, so await app.close() after return is unreachable and never runs.await app.close() must be called before returning the request promise.NestFactory.create(AppModule) and app.init() to fully bootstrap and start the HTTP server before sending requests.request(app.getHttpServer()).post('/items').send({ name: 'item1' }).expect(201) to capture the response object.expect(response.body).toHaveProperty('id') then await app.close() for proper cleanup.Pass the test and this pattern moves unknown