Loading video player…

Watch Two Tests Share One File

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 with shows.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 expected 201 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, with 7 !== 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 with 6 !== 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() and afterEach() 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, which tmpdir() returns. That’s /tmp on Linux, and somewhere else on macOS and Windows. copyFile() puts a copy of shows.json in it, and createApp() 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, as after() did, and then rm() 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:

Language: TypeScript Filename: 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:

Language: Shell
$ 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

00:00 In the last lesson, you tested Niamh’s schedule API through HTTP, on a port the system picked. Every test still reads the same data file, the station’s shows.json.

00:12 Now you’ll watch what that file does to tests that change the schedule.

00:18 Here’s your test file from the last lesson. The before hook starts the app with shows.json, the after hook closes it, and the test expects the station’s six shows.

00:30 Add two new tests below it as you follow along. First, postShow sends a new show as a POST: Saturday Folk, with Freya Lindqvist. The first new test posts it and expects 201 Created.

00:44 The second fetches the list and expects seven shows, the station’s six plus Saturday Folk.

00:53 Run node --test, and watch the data file. The six-show test reads the six shows. Then the create test sends its POST, and the app writes Saturday Folk into shows.json.

01:05 Now the file holds seven shows. Then the list test asks for the shows and gets those seven. All three tests pass. However, look at why the list test passed.

01:19 It counted the one the create test left behind, and never created a show itself. And that’s the station’s real file, the same one your dev server reads.

01:30 Now run the same command again, with no change to the code. Your turn: pause the video and predict whether the list test passes this time.

01:44 It fails. The create test added a second Saturday Folk, so the list test found eight shows, not seven. And last lesson’s test fails too, with seven instead of six.

01:59 Open shows.json and delete the two Saturday Folk entries, so it holds six shows again. Then run only the list test. The test name pattern option runs only the tests whose names contain the text you give it.

02:14 It fails again, with six shows instead of seven. So the list test passes only when the create test runs first, once, on a fresh file. Its result depends on which tests ran before it, and on what they left in the file.

02:32 The fix is to give each test its own copy of the data, and its own server. A new copy needs a new app, because createApp takes the file’s path when it builds the app.

02:44 So before and after become beforeEach and afterEach. They run around every test, one after another, instead of once for the whole file.

02:55 In beforeEach, mkdtemp makes a new, empty folder. It adds six random characters to the start you give it, shows with a dash, so every test gets its own folder.

03:07 The folder goes in the system’s temporary folder, which tmpdir gives you. And join builds the path. Next, copyFile puts a copy of shows.json inside it. And createApp gets that copy’s path, so this test’s server reads and writes there, and nowhere else.

03:27 afterEach waits for the server to close, as after did. Then rm deletes the folder, and the recursive option takes the copy inside with it. The list test needs one more change.

03:40 On its own copy, it would find six shows every time. So it now calls postShow itself and checks that the create worked before it counts.

03:51 Run the suite again. Each test starts with its own six shows. All three pass. Run it once more, and they pass again. Run the list test alone, and it passes too.

04:05 And shows.json still holds the station’s six shows. The tests never touched it.

04:13 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. So far, every request in these tests succeeds.

04:26 In the next lesson, Test the Error Paths Too, you’ll test the requests that should fail.

Become a Member to join the conversation.