Full answer
Hard-coded ports (3000) make tests fail when two test files run at once, or when a developer's app is already running. The clean approach:
- Split the application from the start-up. app.js exports createServer(dependencies) and returns an http.Server (or an Express or Fastify instance). server.js calls listen(process.env.PORT). Tests import app.js only.
- In a test, call server.listen(0, '127.0.0.1'). Port 0 means "any free port". Read it from server.address().port.
- Call the server with fetch (built in), and check status, headers and JSON body.
- Close the server in an after hook (server.close(), and server.closeAllConnections() to avoid waiting for keep-alive connections).
- Inject dependencies: pass a fake database or clock into createServer so the test controls data.
What to test:
- Status codes for success, validation errors and not found.
- Response shape and headers (content type, cache headers).
- Error paths: invalid JSON, large body, a failing dependency answers 500 without leaking details.
- Behaviour, not framework internals.
Frameworks help: Fastify has app.inject() that simulates a request without opening a port, and supertest does something similar for Express. Both are good for speed, but one test with a real socket is still worth having.
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'http-test-'));
fs.writeFileSync(path.join(dir, 'app.js'), `
const http = require('node:http');
// The app is built from its dependencies. Nothing here calls listen().
exports.createServer = ({ students }) => http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
const match = url.pathname.match(/^\\/students\\/(\\d+)$/);
res.setHeader('Content-Type', 'application/json');
if (req.method === 'GET' && match) {
const student = students.find((s) => s.id === Number(match[1]));
res.statusCode = student ? 200 : 404;
return res.end(JSON.stringify(student || { error: 'not found' }));
}
res.statusCode = 405;
res.end(JSON.stringify({ error: 'method not allowed' }));
});
`);
fs.writeFileSync(path.join(dir, 'app.test.js'), `
const { describe, it, before, after } = require('node:test');
const assert = require('node:assert/strict');
const { createServer } = require('./app.js');
describe('students API', () => {
let server, base;
before(async () => {
server = createServer({ students: [{ id: 1, name: 'Asha' }] });
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
base = 'http://127.0.0.1:' + server.address().port;
});
after(() => { server.closeAllConnections(); server.close(); });
it('returns a known student', async () => {
const res = await fetch(base + '/students/1');
assert.equal(res.status, 200);
assert.match(res.headers.get('content-type'), /application\\/json/);
assert.deepEqual(await res.json(), { id: 1, name: 'Asha' });
});
it('returns 404 for an unknown student', async () => {
const res = await fetch(base + '/students/99');
assert.equal(res.status, 404);
});
it('rejects other methods with 405', async () => {
const res = await fetch(base + '/students/1', { method: 'DELETE' });
assert.equal(res.status, 405);
});
});
`);
const run = spawnSync(process.execPath, ['--test', '--test-reporter=tap'], { encoding: 'utf8', cwd: dir });
const lines = run.stdout.split('\n');
console.log(lines.filter((l) => /^\s*(ok|not ok) \d+ - /.test(l)).join('\n'));
console.log('pass:', lines.find((l) => l.startsWith('# pass ')).split(' ')[2], '| fail:', lines.find((l) => l.startsWith('# fail ')).split(' ')[2]);
fs.rmSync(dir, { recursive: true });The app file and the test file are written into a temporary folder, and the test runner is started on it, so the snippet shows the whole setup. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): ok 1 - returns a known student ok 2 - returns 404 for an unknown student ok 3 - rejects other methods with 405 ok 1 - students API pass: 3 | fail: 0
Key points
- Do not call listen in the module that tests import.
- Use port 0 and read server.address().port.
- Close the server in an after hook.
- Inject dependencies so tests control data.
Common mistakes
- Calling listen(3000) inside the module and getting EADDRINUSE in parallel tests.
- Leaving the server open, so the test process never exits.
- Testing with real production data.
- Only testing the happy path.
Follow-ups
- How does Fastify inject differ from a real socket test?
- How would you test authentication middleware?
- How do you test streaming responses?
Tips
- Draw the split: app factory versus start-up file.
- Mention port 0 in the first sentence.
- Say you keep at least one real-socket test.