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 { readFileSync } from "node:fs";
import assert from "node:assert/strict";
interface User { id: number; name: string; }
const raw: string = readFileSync("tests/fixtures/users.json", "utf8");
const users: User[] = JSON.parse(raw) as User[];
assert.equal(users.length, 2);
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 { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const dir: string = mkdtempSync(join(tmpdir(), "suite-"));
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 { rmSync } from "node:fs";
rmSync(dir, { recursive: true, force: true });
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.
Next: Test doubles
Article author: Arthur Isaev