Riverside FM’s schedule API works, but nothing checks that it keeps working. Niamh Gallagher, the station’s volunteer web person, wrote it with no tests. Any change to it, including the ones Gloria’s request line will need, could break GET /shows, and nobody would know until a listener noticed.
So far, you’ve checked an API by sending requests yourself, with curl, and reading what comes back. In this lesson, you’ll hand that job to a test that starts its own copy of the API, sends it a real request with fetch(), and checks the status, the Content-Type header, and the body. Type along in the starting project, with two terminals open. First, get the app ready to be tested.
Build the App Without Starting It
A test needs an app it can start and stop, but Niamh’s server.ts starts listening the moment Node runs it. Open the riverside-schedule folder from the course’s starting project in a terminal, install its packages, and start the API:
$ npm install
$ npm start
> [email protected] start
> node server.ts
Riverside FM schedule API on http://localhost:3000
Leave it running. This is your dev server, the copy you run while you work. In a second terminal, ask it for Gloria’s show. The JSON comes back on one long line, shortened here:
$ curl http://localhost:3000/shows/6
{"id":"6","title":"The Sunday Request Show","host":"Gloria Mendes",...}
Open server.ts. It creates the Express app, registers the five routes, and ends by calling app.listen(PORT), where PORT is 3000 unless the environment says otherwise. A test can’t import the app from this file without also running that last line, and a server started that way would keep listening on 3000 after the tests had finished.
The fix is a factory function, a function that builds the app and hands it back without starting it. Create app.ts, and move everything from server.ts into it except the two constants and the app.listen() call. Then wrap the app’s lines in createApp(), which takes the data file’s path as a parameter:
app.ts
export function createApp(dataFile: string) {
const app = express();
app.use(express.json());
app.get("/shows", async (req, res) => {
res.json(await readShows(dataFile));
});
// The other four routes, with DATA_FILE renamed to dataFile
return app;
}
The imports and the sendError() helper stay at the top of app.ts, above the function. Inside it, each route reads dataFile instead of the DATA_FILE constant, so whoever calls createApp() decides which file the app uses. What’s left of server.ts reads the settings, builds the app, and starts it:
server.ts
import { createApp } from "./app.ts";
const PORT = Number(process.env.PORT ?? 3000);
const DATA_FILE = process.env.DATA_FILE ?? "shows.json";
const app = createApp(DATA_FILE);
app.listen(PORT, (error) => {
if (error) {
console.error(`Couldn't start the API: ${error.message}`);
process.exitCode = 1;
return;
}
console.log(`Riverside FM schedule API on http://localhost:${PORT}`);
});
Express 5 calls the function you pass to app.listen() once the server is listening, or with an error if it can’t start, for example, when another program already has the port. The callback checks for that error first, so a failed start prints the reason and sets a nonzero exit status instead of announcing an API that isn’t there.
Stop the dev server with Ctrl+C, start it again with npm start, and repeat the curl command. Gloria’s show comes back exactly as before, because the routes still answer the same way. Only where the app gets built has changed. A test can now import createApp() from app.ts and start the app itself.
Start the App in a Test Hook
A test has to start a server before its first request and stop it after its last one. You’ve written tests with test() from node:test and checks with assert from node:assert/strict. For a refresher, JavaScript Testing for Pythonistas covers Node’s test runner, comparing it with pytest along the way.
Here, npm test runs node --test, which finds every file whose name ends in .test.ts. What’s new is where the server starts and stops.
node:test has hooks for jobs like this. A function you pass to before() runs once before the file’s tests, and one you pass to after() runs once after them. Your curl command used port 3000, and so does server.ts, so a first attempt naturally starts the test’s app there too. Create shows.test.ts:
shows.test.ts
import { after, before, test } from "node:test";
import assert from "node:assert/strict";
import type { Server } from "node:http";
import { createApp } from "./app.ts";
let server: Server;
before(() => {
const app = createApp("shows.json");
server = app.listen(3000);
});
after(() => {
server.close();
});
The app.listen() call returns Node’s Server object, which the after() hook needs to close the server, so server lives outside both hooks. Below the hooks, add the test itself:
shows.test.ts
test("GET /shows lists the six shows", async () => {
const res = await fetch("http://localhost:3000/shows");
assert.strictEqual(res.status, 200);
assert.strictEqual(
res.headers.get("content-type"),
"application/json; charset=utf-8",
);
const shows = await res.json();
assert.strictEqual(shows.length, 6);
});
Like curl, the test is a client. It sends a real HTTP request and checks what a client relies on. The .get() method of res.headers ignores the header name’s case, and the value is the one Express sends with every res.json() response.
Your dev server is still running in the first terminal. Before you run npm test in the second, decide what you expect: Does the test pass, and which server answers its request?
The test passes, and the file fails anyway. The error line is long, so it’s shortened here:
$ npm test
> [email protected] test
> node --test
✔ GET /shows lists the six shows (55.464736ms)
ℹ Error: Test hook "before" ... created the error "Error: listen EADDRINUSE ...
✖ shows.test.ts (318.530952ms)
ℹ tests 2
ℹ suites 0
ℹ pass 1
ℹ fail 1
...
EADDRINUSE means the address is already in use: only one server can listen on a port at a time, and the dev server got there first. The test’s server never started, so the passing test checked the dev server.
You can confirm which server answered. Add this line to the test, right after the fetch() call, and run npm test again:
shows.test.ts
console.log("Test server listening:", server.listening);
The output starts with the line it logs, above the same check mark:
Test server listening: false
✔ GET /shows lists the six shows (51.328515ms)
...
The test’s own server isn’t listening, yet the request to port 3000 succeeded, because the dev server answered it. Delete the console.log() line before you go on.
That’s the trouble with a fixed port. With the dev server stopped, the same file passes cleanly. With it running, the tests check whatever the dev server happens to run, possibly an outdated version of your code, and the hook’s failure shows up as an uncaught error after the test instead of a failing hook.
If a passing check mark next to a server that never started still puzzles you, then click the button below. It opens a conversation with the AI mentor with this question ready to send, and you can follow up in your own words until it makes sense:
Let the System Pick a Port
The test needs a port nobody else is using, and it can’t know in advance which ports are free. Port 0 solves that. When a server listens on port 0, the operating system gives it any free port. Add the once import below the other imports, declare a base variable below server, and replace the before() hook:
shows.test.ts
import { once } from "node:events";
let server: Server;
let base: string;
before(async () => {
const app = createApp("shows.json");
server = app.listen(0);
await once(server, "listening");
const address = server.address();
if (address === null || typeof address === "string") {
throw new Error("The test server isn't on a port.");
}
base = `http://localhost:${address.port}`;
});
The app.listen() call only starts the server, and the server emits a "listening" event once it’s ready. The once() function from node:events returns a promise that resolves on that event, or rejects if the server emits an error instead. The hook is async, so node:test waits for it. If the port is taken, startup now fails inside the hook, where you can see the error.
Next, the hook asks the server where it ended up. The server.address() method returns an object such as { address: '::', family: 'IPv6', port: 41769 }, with the port the system picked for this run.
The method can also return a string for a server on a local socket, or null for one that isn’t listening. The if check rules both out before the hook reads .port. Then the hook builds base, the URL prefix for every test request.
Stopping the server has the same gap in reverse. The server.close() method only starts the shutdown. It stops the server from taking new connections, then calls its callback once the open ones have finished, or with an error if the server wasn’t running. Replace the after() hook so it waits for that callback:
shows.test.ts
after(async () => {
await new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
});
});
The promise resolves when the server has closed and rejects if closing fails. Because the hook is async and awaits it, node:test now waits for shutdown as well as startup, and a failed close shows up as a failing hook.
Now point the test at base, and check more than the body’s length. Replace the test with this version:
shows.test.ts
test("GET /shows lists the six shows", async () => {
const res = await fetch(`${base}/shows`);
assert.strictEqual(res.status, 200);
assert.strictEqual(
res.headers.get("content-type"),
"application/json; charset=utf-8",
);
const shows = await res.json();
assert.strictEqual(shows.length, 6);
assert.deepStrictEqual(shows[5], {
id: "6",
title: "The Sunday Request Show",
host: "Gloria Mendes",
day: "Sunday",
start: "10:00",
minutes: 120,
});
});
The assert.deepStrictEqual() check compares every field of the last show with the JSON you saw from curl. Run the tests with the dev server still running:
$ npm test
> [email protected] test
> node --test
✔ GET /shows lists the six shows (52.824425ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 338.125111
The run passes with no error, and it would pass the same way with the dev server stopped. You still need the after() hook. An open server keeps its process alive, which is what you want from server.ts. Without server.close(), the check mark appears and npm test never finishes.
Before you add another test, check that you can explain the new hooks. This button asks the AI mentor to quiz you on your before() hook, one question at a time:
Each process now has its own server, but the servers still have one thing in common:
The test’s server reads shows.json because that’s the path the test passes to createApp(). Keep that shared file in mind. Sharing the file doesn’t matter while the test only reads.
Check Your Test
Answer these with your test file open:
- Kwame starts the dev server, then runs a test file whose
before()hook callsapp.listen(3000)and whose test fetcheshttp://localhost:3000/shows. The check mark is green. Which server answered, and what else does the run report? - Write a second test in
shows.test.tsforGET /shows/3. It should check the status and theContent-Typeheader and confirm that the body describes Hana Sato’s Late Jazz show, on Fridays at 22:00 for 120 minutes. - You delete the
after()hook. What doesnpm testdo, and why?
Question 1: The dev server answered. The test’s server failed to listen with EADDRINUSE, which arrives as an uncaught error, so the file fails even though the test passed. Listening on port 0 and building the URL from server.address().port gives the test its own server.
Question 2: The test can reuse base from the before() hook and compare the whole body at once:
shows.test.ts
test("GET /shows/3 finds Late Jazz", async () => {
const res = await fetch(`${base}/shows/3`);
assert.strictEqual(res.status, 200);
assert.strictEqual(
res.headers.get("content-type"),
"application/json; charset=utf-8",
);
assert.deepStrictEqual(await res.json(), {
id: "3",
title: "Late Jazz",
host: "Hana Sato",
day: "Friday",
start: "22:00",
minutes: 120,
});
});
Both tests share the one server the hooks start, and npm test reports two passes.
Question 3: The tests pass, but the run never finishes. The test’s server is still listening, and an open server keeps the process alive until something closes it.
Your test now talks to its own server, on a port nobody else is using. But it still reads the same shows.json as the dev server, and as soon as a test writes to that file, other tests start seeing its changes. In the next lesson, Watch Two Tests Share One File, you’ll see what that does to a test suite.