Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท Concepts and Pitfalls

Testing HTTP servers in Node.js

Test a Node.js HTTP server with node:test: listen on port 0, call it with fetch, assert on status and body, and shut down cleanly so tests never hang.

Testing an HTTP server means starting it for real, sending it a request and checking the response. Node.js ships everything you need: node:http to build the server, the built-in fetch() to call it, and node:test plus node:assert to run and judge the checks. No extra packages and no mocking of the network are required, because a server bound to the loopback address is fast enough to start once per test file.

Three habits make these tests reliable. Listen on port 0 so the operating system picks a free port and parallel test files never collide. Read the real port back from server.address(). And close the server (and any kept-alive connections) in an after() hook so the test process can exit.

Try it

Node.js A server, a client and two assertions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Separating the app from the listener

The easiest server to test is one whose request handler is a plain function. Export the handler (or a function that builds the server) from one module and call listen() only in the entry file. A test then creates its own instance. The same idea applies to frameworks: export the app, never call listen() on import.

Node.js A handler factory and a small helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The moving parts

Step Code Why
Start server.listen(0, '127.0.0.1', cb) Port 0 asks the OS for a free port; the loopback host keeps the server private.
Discover server.address().port The only way to know which port was chosen.
Call await fetch(url) Real HTTP, so headers, status lines and bodies are exercised.
Stop server.closeAllConnections(); server.close() Keep-alive sockets otherwise hold the server open.

Usage notes

  • Never hard-code a port. A fixed port fails when two test files run at the same time (the test runner runs files in separate processes in parallel) or when a developer already runs the app.
  • Bind to 127.0.0.1. Without a host, listen() may bind to all interfaces, which triggers firewall prompts on some machines and exposes test servers.
  • fetch() keeps connections alive. server.close() stops accepting new connections but waits for open ones. Call server.closeAllConnections() first (added in Node.js 18.2) or the test file can hang until the idle timeout. closeIdleConnections() is the gentler variant.
  • Await the close. server.close() takes a callback or emits 'close'; wrap it in a promise when a later step depends on the port being free.
  • 404 and 500 do not reject. fetch() resolves for any HTTP status; assert on res.status or res.ok. Only network failures reject.
  • Always consume or cancel the body of responses you do not read, for example with await res.arrayBuffer() or res.body.cancel(), so the connection can be reused or closed.
  • Add a deadline. Pass signal: AbortSignal.timeout(2000) to fetch() so a handler that never answers fails the test quickly instead of hanging. See AbortSignal.
  • Test the failure paths too: malformed JSON, missing headers, wrong methods and oversized bodies are the cases that break in production.
  • One server per file or per test? One per file with before()/after() is fastest; one per test (as in withServer()) isolates state. Starting a loopback server takes a few milliseconds, so isolation is usually affordable.