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.
NestJS
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.
app.e2e-spec.ts
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.
app.e2e-spec.ts
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.
Related guides
NestJS TestingModule missing app.init() in CIFix NestJS TestingModule tests that fail because app.init() was never called in CI - guards, interceptors, an…
NestJS "Nest application failed to start" in CIFix "Error: Nest application failed to start" in CI - a lifecycle hook, module init, or async provider threw…
NestJS "EADDRINUSE: address already in use" in e2e in CIFix NestJS "listen EADDRINUSE: address already in use :::3000" in e2e in CI - a previous test app was not clo…