Fixtures

Small JSON fixtures

A fixture is a small frozen input that tests reuse. Real responses copied once into a JSON file beat invented values typed by hand, because the shape stays honest. Keep fixtures tiny: two users prove a list works, and two hundred prove nothing new:

[ { "id": 1, "name": "Ada" }, { "id": 2, "name": "Bob" } ]

Two rows cover the empty-versus-many question well enough for most list logic. Add rows only when a test demands a new shape, not for comfort.

Load in tests

Read the fixture with the same file call the product uses, then parse the text into a typed value. An interface states the expected shape, and a type assertion pins the parsed result to it:

import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import assert from "node:assert/strict"; interface User { id: number; name: string; } mkdirSync("tests/fixtures", { recursive: true }); writeFileSync("tests/fixtures/users.json", JSON.stringify([ { id: 1, name: "Ada" }, { id: 2, name: "Bob" }, ])); const raw: string = readFileSync("tests/fixtures/users.json", "utf8"); const users: User[] = JSON.parse(raw) as User[]; assert.equal(users.length, 2); console.log("users loaded: " + users.map((user) => user.name).join(", "));

users loaded: Ada, Bob

The utf8 flag keeps the result a string instead of bytes. From here the test works with plain typed users, exactly as if the data had arrived from the network.

Temp dirs

Tests that write files need a scratch folder. mkdtempSync creates a uniquely named temp dir from a prefix, inside the OS temp area. A suite prefix keeps the folder recognizable among strangers:

import { existsSync, mkdtempSync, statSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; const dir: string = mkdtempSync(join(tmpdir(), "suite-")); console.log("temp dir is a folder: " + statSync(dir).isDirectory()); console.log("temp dir exists: " + existsSync(dir));

temp dir is a folder: true
temp dir exists: true

The output reports the folder as a fact and never prints its random name, so the lines stay the same on every run. Random characters appended to the prefix stop parallel runs from stepping on each other. Every run starts with a fresh empty dir, so leftover files can never poison the results.

Clean after

Delete what the test created. Remove the temp dir at the end of the run, so stale files never leak into the next one and cause mystery failures. rmSync with the recursive and force flags removes the folder whether it holds files or not:

import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; const dir: string = mkdtempSync(join(tmpdir(), "suite-")); writeFileSync(join(dir, "note.txt"), "hello"); rmSync(dir, { recursive: true, force: true }); console.log("folder gone: " + !existsSync(dir)); rmSync(dir, { recursive: true, force: true }); console.log("second remove did not throw");

folder gone: true
second remove did not throw

The first line reports the folder as gone without printing its path, and the second remove runs on a missing folder and survives, which is what force promises. force also covers the missing folder case, so cleanup never throws on an already clean slate. Create, use, delete: the folder exists only while the test runs.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is a test fixture?

    Answer

    A small frozen input that several tests reuse

    A fixture is stored input, often a JSON file copied from a real response, and each test reads the same honest shape.

  2. Why does this lesson keep fixtures tiny?

    Answer

    Two users prove the list logic, and more rows add noise instead of proof

    A couple of rows show the empty-versus-many case, and extra rows test nothing new while making failures harder to read.

  3. Why pass "utf8" to readFileSync for a fixture?

    Answer

    It returns a string instead of a buffer, ready for JSON.parse

    Without the flag the call returns bytes, and the parsed text needs the string that the utf8 flag gives.

  4. Why give mkdtempSync a prefix such as suite-?

    Answer

    The prefix makes the temp folder recognizable among other folders

    The random part keeps parallel runs apart, and the prefix lets a person see which suite left the folder behind.

  5. Why does cleanup use rmSync(dir, { recursive: true, force: true }) instead of plain rmSync(dir)?

    Answer

    Plain rmSync refuses a folder that still holds files, while recursive removes them and force tolerates a missing folder

    A test folder usually holds files, and the second run may already be clean, so the flags cover both cases without a branch.

  6. What does this program print? interface User { id: number; name: string; } const users: User[] = [ { id: 1, name: "Ada" }, { id: 2, name: "Bob" }, ]; console.log(users.length);

    Answer

    2

    The array holds two users, and its length is the number two.

  7. What does this program print? import { readFileSync, writeFileSync } from "node:fs"; writeFileSync("users.json", JSON.stringify([{ id: 1 }, { id: 2 }])); const raw: string = readFileSync("users.json", "utf8"); console.log(JSON.parse(raw).length);

    Answer

    2

    The file holds a JSON array of two objects, and parsing the text gives an array whose length is two.

  8. What does this program print? import { existsSync, mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; const dir: string = mkdtempSync(join(tmpdir(), "suite-")); console.log(existsSync(dir));

    Answer

    true

    mkdtempSync creates the folder before it returns its name, so the path exists at once.

  9. What does this program print? import { existsSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; const dir: string = mkdtempSync(join(tmpdir(), "suite-")); rmSync(dir, { recursive: true, force: true }); console.log(existsSync(dir));

    Answer

    false

    The remove call deletes the folder, and the check afterwards finds nothing at that path.

  10. A test writes users.json into the project folder and never deletes it. What is the danger?

    Answer

    The next run reads a stale file and fails for a reason that has nothing to do with the code

    A file left behind outlives the test that made it, and a later run may pick up old data; cleanup keeps the folder empty between runs.

Article author: Arthur Isaev