Skip to content
Tutorials Center
My learning

Topics

Lesson 103 of 133 ยท Testing

Testing HTTP Servers and CLIs

Learn to test Node.js HTTP servers on port 0 with fetch, test middleware in isolation, test command-line tools with child processes, and use fixtures and data builders.

Unit tests for pure functions are easy. The code that makes a Node.js program useful is not pure: it listens on a port, reads request bodies, writes headers, spawns processes and prints to the terminal. Many developers skip testing that layer because it feels like it needs a browser or a deployment. It does not. A Node.js program can start its own server on a free port, call it with fetch, check the answer and shut it down, all inside one test file and in a few milliseconds.

This lesson shows the patterns: starting a server on port 0, closing it reliably, testing middleware without any network, testing command-line tools by running them as child processes, and organizing test data so tests stay readable. It builds on the test runner, assertions and mocks, and the code under test uses what you learned in Building an HTTP Server and Routing.

The test runner prints the duration of every test in milliseconds. Those numbers change from run to run, so the lessons never quote them. Only the pass and fail marks matter.

Design for testing: export the server, do not start it

The most important decision is made before you write any test: separate creating a server from listening. If your server.js calls listen(3000) at the top level, importing it for a test starts a real server on a fixed port, and two test files will fight over that port.

Export a function that builds the server (or the request handler) and let a tiny main file call listen:

NODE
// app.js - exports, does not listen
import http from 'node:http';

export function createApp() {
  return http.createServer((req, res) => { /* ... */ });
}
NODE
// main.js - the only file that picks a port
import { createApp } from './app.js';
createApp().listen(Number(process.env.PORT ?? 3000));

Tests import createApp() and decide for themselves where it listens.

Port 0 and the lifecycle

Listening on port 0 asks the operating system for any free port. After listen finishes, server.address().port tells you which one. Because every test run gets its own port, tests never collide with each other or with something else on your machine. Always bind to 127.0.0.1 so the test server is not reachable from the network.

The lifecycle belongs in hooks: start in before, stop in after. The runner awaits both, so a promise-returning hook is enough.

Node.js A test file with a real server on port 0

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.

Read the structure, because you will copy it for every server you test. before waits for the listen callback, then builds the base URL from the real port. Each it is a plain fetch call followed by assertions on the status, headers and body. after closes the server. Note that the second test adds a todo to shared state, so test order matters in this example. The section on test data below shows how to avoid that coupling.

Why closing matters

server.close() stops accepting new connections and calls its callback once the existing ones end. If you forget it, the open listening socket keeps the event loop alive and the test process never exits. In CI this appears as a job that hangs until it is killed. A second trap: fetch keeps connections alive for reuse, so server.close() can wait for idle keep-alive sockets. Node 19 and newer close idle connections on close(), and server.closeAllConnections() exists for the stubborn case (a streaming response that never ends).

Create one server per test file (in before) rather than one per test. Starting a server is cheap, but doing it 200 times adds up. Reset the state you care about in beforeEach instead.

Giving each test fresh state

The previous example had tests that depend on each other through the shared todos array. Tests that depend on order are fragile: run one alone with --test-name-pattern and it fails. The fix is to let the app factory take its state as an argument (dependency injection again) and to rebuild the server in beforeEach.

Node.js A fresh server and data for every test

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 second test would fail if the first had deleted the lamp from shared state, but because the store is rebuilt before each test, it passes in any order. The server per test costs a fraction of a millisecond.

Testing middleware without a network

Middleware is a function (req, res, next). You do not need a socket to test one: pass plain objects that have only the properties the middleware touches, and a next that is a mock function. The result is faster and the test points straight at the failing line. (Middleware design is explained in Middleware.)

Node.js Testing middleware with fake req and res

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 fake res is twelve lines, and it also documents exactly which parts of the response API the middleware uses. When a fake grows beyond twenty lines, that is a hint to switch to a real server for that test.

Testing a command-line tool

A CLI is a program with inputs (arguments, standard input, environment variables) and outputs (standard output, standard error, an exit code). The most honest test runs the program as a separate process and checks those outputs. You do that with child_process (see Child Processes). Use process.execPath to run the same Node binary that runs your tests, which avoids problems with PATH and versions.

To keep the example self-contained, the test writes the CLI script into the current directory first. In your own project the script would already be a file, such as bin/wordcount.js.

Node.js Running a CLI as a child process

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.

Three habits make CLI tests dependable. First, check the exit code and stderr as well as stdout: a tool that prints the right text and exits with 0 after failing is a bug in a shell script. Second, feed input through stdin instead of files where possible, so the test needs no fixtures on disk. Third, keep the logic out of the CLI file. If the real work lives in an importable function (countWords(text)), you can unit test it in microseconds and need only two or three process-level tests to prove the wiring: the argument parsing, the output format and the exit codes. Writing the CLI itself is the topic of CLI Tools.

Fixtures and test data builders

A fixture is data a test needs: a JSON file, a sample CSV, a pre-filled database. Keep small fixtures inline in the test, where the reader sees the input next to the expectation. Move large ones to a test/fixtures/ folder and load them with import.meta.dirname, which gives the folder of the current file regardless of where the tests are launched from.

NODE
import { readFile } from 'node:fs/promises';
import path from 'node:path';

const sample = await readFile(path.join(import.meta.dirname, 'fixtures', 'orders.csv'), 'utf8');

When objects are big but tests care about only one field, use a data builder: a function that returns a valid default and lets the test override the interesting part. The test then states only what matters.

Node.js A test data builder

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.

Each test names only the field it cares about (country, items). When the order shape gains a new required field, you change the builder once instead of editing fifty tests.

Snapshot tests

A snapshot test stores the output of your code in a file the first time it runs and compares future runs to that file. It is handy for large, stable output such as a rendered HTML page or a long error report. The test runner provides it through t.assert.snapshot(value); you create or refresh the snapshot files with the --test-update-snapshots flag, and the files are committed to git so changes show up in code review. In Node 24 this feature is still marked experimental, and it needs files on disk and a flag, so it is shown read-only here.

NODE
// Read-only: run with  node --test --test-update-snapshots  the first time
import { test } from 'node:test';

test('renders the invoice page', (t) => {
  const html = renderInvoice({ number: 1042, total: 99.5 });
  t.assert.snapshot(html);
});

Use snapshots sparingly. A huge snapshot nobody reads gets "updated" blindly whenever it fails, and then it protects nothing. For small values, an explicit assert.deepStrictEqual documents the intent far better.

What to test at which level

A healthy suite mixes three levels:

  1. Unit tests for pure logic: thousands, milliseconds.
  2. Handler or middleware tests with fakes: hundreds, still instant.
  3. HTTP and CLI tests against the real wiring: a few dozen. They prove the routes, headers, status codes and exit codes work together.

Test the failure paths too: malformed JSON in a body, a missing header, a 404, a request that is too large. Those paths are where production incidents live. Security headers and cookies (see Headers, Cookies and Caching) deserve explicit assertions as well, because nobody notices when they silently disappear.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why start a test server on port 0?

    Listening on port 0 asks the OS for any free port. Read it from server.address().port, so parallel test files and other programs cannot conflict.
  2. 2. What happens if a test file starts a server in before() but never closes it?

    A listening socket keeps the event loop busy. Without server.close() the test process does not exit by itself.
  3. 3. Why export a createApp() function instead of calling listen() at the top of app.js?

    Separating creation from listening lets each test choose its own port (or none) and keeps imports free of side effects.
  4. 4. A CLI test checks stdout is correct. What else should it check?

    A tool can print plausible output and still exit with the wrong code or write errors to stderr. Scripts and CI rely on the exit code.
  5. 5. What is a test data builder for?

    A builder hides the boilerplate fields. The test states only what matters, and a new required field needs a change in one place.

Summary

  • Export a function that creates the server; only a separate main file calls listen.
  • In tests, listen on 127.0.0.1 port 0, read server.address().port, call it with fetch, and close it in after or afterEach.
  • Rebuild state per test (inject the store) so tests pass in any order.
  • Test middleware with plain-object requests and responses and a mock next.
  • Test CLIs as child processes with process.execPath: assert on stdout, stderr and the exit code, and feed input through stdin.
  • Use inline fixtures, files loaded through import.meta.dirname and data builders; use snapshots sparingly.
  • Keep most tests small and fast, and add a few end-to-end tests for the wiring.

Next: Test-Driven Development Workshop