NestJS e2e "supertest ... ECONNREFUSED" (app not initialized) in CI
supertest hit a connection refused because the Nest application was not initialized before the request, or the test targeted a hardcoded host/port instead of the in-memory app instance.
What this error means
An e2e spec fails with "Error: connect ECONNREFUSED 127.0.0.1:3000". The HTTP server the test expected was never started or bound.
Error: connect ECONNREFUSED 127.0.0.1:3000
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16)Common causes
app.init() was not awaited before requests
supertest was passed the HTTP server before await app.init() completed, so nothing is listening yet.
The test targets a URL string instead of the app
Passing request('http://localhost:3000') requires a separately running server; the in-memory app never bound that port.
How to fix it
Init the app and pass its HTTP server
- Create the app from a compiled TestingModule.
- Await
app.init()in beforeAll before any request. - Pass
app.getHttpServer()to supertest so no real port is needed.
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
app = moduleRef.createNestApplication();
await app.init();
});
it('/health', () => request(app.getHttpServer()).get('/health').expect(200));Close the app after the suite
Call await app.close() in afterAll so a leaked server does not affect later suites.
afterAll(async () => { await app.close(); });How to prevent it
- Always pass
app.getHttpServer()to supertest, never a URL. - Await app.init() in beforeAll and close in afterAll.
- Avoid hardcoded ports in e2e tests.