When testing an Express 5 app with Supertest, why does app.js export the app and leave app.listen to a separate entry file?
answer
- an Express app is a function
- who owns the port
- ephemeral port, then closed
- fixed port across test processes
basics
~20 sSupertest's request(app) takes the Express app, a plain request-handler function, and runs it on its own server on an ephemeral port, closed afterwards. An app module that calls listen grabs a fixed port at import and keeps the test process from exiting.
solid answer
~30 sAn Express app is a function with the `(req, res)` shape, so Supertest's `request(app)` can wrap it in `http.createServer(app)`, bind that server to port 0 on `127.0.0.1` and close it once the last request it started has settled. If `app.js` calls `app.listen(3000)` at import, every test file that requires it also opens port 3000: parallel test processes collide with `EADDRINUSE`, and the server nobody closes keeps the event loop alive, so the run may not exit. The house split is `app.js` building and exporting the app, and a small `server.js` that requires it and calls `app.listen(process.env.PORT)`. Tests import only `app.js`.
code
javascript · 10 linesconst express = require('express');
const app = express();
app.use(express.json());
app.get('/api/health', (req, res) => {
res.json({ status: 'ok' });
});
module.exports = app; // no app.listen() herego deeper
Remember that request(app) takes the Express app itself and that app.js should export it without calling listen.
Explain that express() returns a request-listener function, that Supertest wraps it in its own server on port 0, and that it closes that server when its requests finish.
Diagnose a suite that hangs after passing or fails with EADDRINUSE in parallel runs, and trace both back to a listener opened as an import side effect.
Set the convention that app modules are side-effect free and startup lives in one entry file, so every service is testable the same way.
## What Supertest actually needs **Supertest** is a library for testing HTTP servers: you hand it something to talk to, describe a request with chained calls such as `.get('/api/health')`, and assert on the response. Its entry point, `request()`, accepts three kinds of target: - **a function**, such as an Express app, which it wraps in a fresh `http.createServer(app)`; - **an `http.Server`** you created yourself, which it uses as given; - **a URL string**, such as a server already running elsewhere. An Express app qualifies as a function because `express()` returns one: the app is itself the request listener with the `(req, res)` shape that Node's HTTP server calls. Express's own `app.listen()` is a convenience: it creates `http.createServer(this)`, calls `listen(...)` on that server with your arguments and returns the server. ## What request(app) does with the app When the first request is described on a server that is not listening yet, Supertest: 1. calls `listen(0, '127.0.0.1')`, so the operating system picks a free **ephemeral port** and nothing else can be reached by accident; 2. waits for the `listening` event, then sends the request over a real loopback TCP connection; 3. counts the requests in flight on that server and calls `server.close()` when the last one settles. Every `request(app)` call builds its own server, so two tests never share a port and you never pick one. A server you pass in that is **already listening** is treated differently: Supertest uses its address and leaves it open, because it only closes servers it started itself. ## Why app.js must not call listen If the module that builds the app also calls `app.listen(3000)`, then importing it for a test has a side effect: a second server on a fixed port, separate from the one Supertest creates. Three things follow. - **Port collisions.** Test runners commonly run test files in separate processes. Each process imports `app.js`, each tries port 3000, and the second fails with `listen EADDRINUSE`. - **A process that will not exit.** Supertest closes its own server, but the one `app.js` opened is still listening, and an open server keeps Node's event loop alive. The tests pass and the run then hangs or has to be killed. - **Lost control.** The test cannot choose the port, the host or when that server stops. None of this is a Supertest limitation: it is what happens whenever a module starts a listener as an import side effect. ## The usual layout | File | Responsibility | Imported by tests? | |---|---|---| | `app.js` | create the app, mount middleware and routes, register error handlers, `module.exports = app` | yes | | `server.js` | require the app, read `PORT`, call `app.listen()`, wire process signals | no | The production start command runs `node server.js`; the tests require `app.js` and pass it to `request(app)`. Startup work that genuinely has to happen before requests (opening a database pool, loading configuration) is best exposed as a function the entry file awaits before `listen`, so a test can call it, or replace it, without opening a port. ## Common variations - **Factory instead of singleton.** `module.exports = function createApp(deps) { ... }` lets each test build an app with fakes injected. `request(createApp(fakes))` works the same way, because the factory still returns an Express app function. - **ES modules.** `export default app` in `app.js` and `import app from './app.js'` in the test; nothing else changes. - **Testing a real listening server.** When a test genuinely needs the server object (to exercise something on it), create it in the test with `http.createServer(app)`, listen on port 0, pass the server to `request()` and close it yourself afterwards. - **HTTP/2.** `request(app, { http2: true })` wraps the app in an HTTP/2 server instead of an HTTP/1.1 one; the export-without-listen rule is the same. - **Several requests, one server object.** Requests made from one `const api = request(app)` share that factory's server: Supertest closes it whenever no request on it is in flight and listens on port 0 again for the next one, while a second `request(app)` call wraps the app in a different server. ## What to say in an interview The short version: Express apps are functions, Supertest turns the function into a server it owns on an ephemeral port, and a module that listens on import makes every test process open a fixed port that nothing closes. Exporting the app and listening in a separate entry file keeps the app importable without side effects. A strong answer adds the symptoms that reveal the mistake, a suite that passes and then hangs, or parallel runs failing with `EADDRINUSE`, and names the fix as a file layout rather than a test-runner flag.
- If you pass Supertest the server returned by app.listen(3000) instead of the app, what changes?Supertest sees a server that is already listening, so it sends requests to that server's address and does not close it: it only closes servers it started. The test now depends on port 3000 being free, and the test must call `server.close()` itself or the process stays alive.
- Does request(app) exercise a real network connection or call the app in-process?A real one. Supertest listens on an ephemeral port on `127.0.0.1` and sends the request over a loopback TCP connection, so Node's HTTP parser, headers and status line are all real. What it does not exercise is anything in front of the app in production, such as a proxy or load balancer.
- Supertest needs the app to be listening on a known port first.
- Calling app.listen in app.js is harmless because tests reuse that server.
- request(app) calls the route handlers directly without any HTTP.
- Supertest leaves its ephemeral server running until the test process exits.
- Every test should pick a unique port number to avoid collisions.