In this lesson, you watched tests for Niamh’s schedule API share the station’s shows.json, saw one pass only because of another, and gave each test a fresh copy of the data of its own.
Key Points
- Three tests, one data file. The
before()hook from the last lesson started the app withshows.json, so every test talked to the same server and the same file. Below the test that expects six shows, you added two: “POST /shows creates a show” posted Saturday Folk, with Freya Lindqvist, and expected201 Created, and “GET /shows lists the new show with the others” expected seven shows, the station’s six plus Saturday Folk. - The first run passed for the wrong reason. The create test wrote Saturday Folk into
shows.json, and the list test counted the show the create test left behind. It never created one itself. And that was the station’s real file, the same one your dev server reads. - The same command failed the second time. With no change to the code, the create test added a second Saturday Folk, and the list test failed with
8 !== 7. The test from the last lesson failed too, with7 !== 6. - Alone, it failed too. After you deleted the two Saturday Folk entries from
shows.json,node --test --test-name-pattern="with the others"ran only the tests whose names contain that text, and the list test failed with6 !== 7. It passed only when the create test ran first, once, on a fresh file. Its result depended on which tests ran before it and what they left in the file. - Each test gets its own server, too.
createApp()takes the file’s path when it builds the app, so a new copy needs a new app.beforeEach()andafterEach()run around every test, one after another, instead of once for the whole file. mkdtemp()makes a new, empty folder. It adds six random characters to the start you give it,shows-, so every test gets its own folder, such as/tmp/shows-9FF1ww.join()builds the folder’s path inside the system’s temporary folder, whichtmpdir()returns. That’s/tmpon Linux, and somewhere else on macOS and Windows.copyFile()puts a copy ofshows.jsonin it, andcreateApp()gets that copy’s path, so the test’s server reads and writes there and nowhere else.afterEach()cleans up. It waits for the server to close, asafter()did, and thenrm()with{ recursive: true }deletes the folder and the copy inside it.- Each test creates what it needs. The list test needs one more change. On its own copy, it would find six shows every time. So it calls
postShow()itself and checks that the create worked before it counts. - The fixed suite passes, run after run. It passed twice in a row, and the list test passed alone. The tests never touched
shows.json, which still holds the station’s six shows. - The rule: give each test fresh data of its own, and let it create what it needs. Then it passes alone, in any order, or with the rest of the suite.
Here’s the test file with a fresh copy of the data for every test, shows.test.ts:
shows.test.ts
import { afterEach, beforeEach, test } from "node:test";
import assert from "node:assert/strict";
import { once } from "node:events";
import { copyFile, mkdtemp, rm } from "node:fs/promises";
import type { Server } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createApp } from "./app.ts";
let server: Server;
let base: string;
let dir: string;
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), "shows-"));
const dataFile = join(dir, "shows.json");
await copyFile("shows.json", dataFile);
const app = createApp(dataFile);
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}`;
});
afterEach(async () => {
await new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
});
await rm(dir, { recursive: true });
});
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,
});
});
const saturdayFolk = {
title: "Saturday Folk",
host: "Freya Lindqvist",
day: "Saturday",
start: "14:00",
minutes: 90,
};
function postShow() {
return fetch(`${base}/shows`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(saturdayFolk),
});
}
test("POST /shows creates a show", async () => {
const res = await postShow();
assert.strictEqual(res.status, 201);
});
test("GET /shows lists the new show with the others", async () => {
const created = await postShow();
assert.strictEqual(created.status, 201);
const res = await fetch(`${base}/shows`);
const shows = await res.json();
assert.strictEqual(shows.length, 7);
});
Here’s a run of it, with node --test:
$ node --test
✔ GET /shows lists the six shows (67.809292ms)
✔ POST /shows creates a show (20.53588ms)
✔ GET /shows lists the new show with the others (11.971086ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 386.879945