Skip to content

Reset Shared State Between Tests

The Course
•
18 min study

The decision

Tests in one file share one process, so they share every module-level value. If a test adds an item to a shared practice list, the next test starts with that item. Tests then pass in one order and fail in another, and order starts to look like correctness. The fix is to give every test its own fresh copy of the starting data, a fixture.

Read, predict, run

lib/contract.js makes a fixture from a seed: a new array of new row objects:

JavaScript
export function run(seed) {
  return seed.map((row) => ({ ...row }));
}

tests/fixture.test.js checks that changing a copy can't reach the seed:

JavaScript
test("changing a copied row leaves the seed alone", () => {
  const seed = [{ id: 1, title: "Routing" }];
  const rows = run(seed);
  rows[0].title = "Changed";
  assert.deepEqual(seed, [{ id: 1, title: "Routing" }]);
});

test("changing a copied row's tags leaves the seed's tags alone", () => {
  const seed = [{ id: 1, tags: ["react"] }];
  const rows = run(seed);
  rows[0].tags.push("changed");
  assert.deepEqual(seed, [{ id: 1, tags: ["react"] }]);
});

Predict which of the two tests passes before you run.

Reset Shared State Between Tests Next.js · 8 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; import Tests from "./Tests.jsx"; export default function Page() { return ( <main> <h1>Reset Shared State Between Tests</h1> <Tests /> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } import "@/tests/fixture.test.js"; import { runTests } from "@/lib/test.js"; export default async function Tests() { const results = await runTests(); return ( <section> <h2>Tests in tests/fixture.test.js</h2> <p> Tests: {results.filter((r) => r.pass).length}/{results.length} passed </p> <ul> {results.map((r) => ( <li key={r.name} className={r.pass ? "pass" : "fail"}> {r.pass ? "✓" : "✗"} {r.name} {r.message && `: ${r.message}`} </li> ))} </ul> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run(seed) { return seed.map((row) => ({ ...row })); } export const examples = [ [[{ id: 1, title: "Routing" }], [{ id: 1, title: "Routing" }]], ]; // A tiny stand-in for node:test and node:assert/strict, so tests can run in // the browser. On your computer, write instead: // import { test } from "node:test"; // import assert from "node:assert/strict"; const tests = []; export function test(name, fn) { tests.push({ name, fn }); } const show = (value) => JSON.stringify(value) ?? String(value); export const assert = { equal(actual, expected) { if (!Object.is(actual, expected)) throw new Error(`expected ${show(expected)}, got ${show(actual)}`); }, deepEqual(actual, expected) { if (show(actual) !== show(expected)) throw new Error(`expected ${show(expected)}, got ${show(actual)}`); }, }; export async function runTests() { const results = []; for (const { name, fn } of tests) { try { await fn(); results.push({ name, pass: true, message: "" }); } catch (error) { results.push({ name, pass: false, message: error.message }); } } return results; } import { test, assert } from "@/lib/test.js"; import { run } from "@/lib/contract.js"; test("changing a copied row leaves the seed alone", () => { const seed = [{ id: 1, title: "Routing" }]; const rows = run(seed); rows[0].title = "Changed"; assert.deepEqual(seed, [{ id: 1, title: "Routing" }]); }); test("changing a copied row's tags leaves the seed's tags alone", () => { const seed = [{ id: 1, tags: ["react"] }]; const rows = run(seed); rows[0].tags.push("changed"); assert.deepEqual(seed, [{ id: 1, tags: ["react"] }]); });
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction

The first passes and the second fails:

Text
✗ changing a copied row's tags leaves the seed's tags alone: expected [{"id":1,"tags":["react"]}], got [{"id":1,"tags":["react","changed"]}]

{ ...row } copies the row's properties one level deep. title is a string, so the copy has its own. tags is an array, so the copy gets the same array, and push on the copy's tags changes the seed's too.

The failure to avoid

A check that compares a fresh result with an expected value can't catch this: the result looks right until someone changes it. That's why the test changes the copy and then looks at the seed. The old version of this exercise compared only the returned rows, and it passed before any fix.

Exercise

Copy the nested array

Change run so both tests pass. Copy each row's tags array as well, keep the rest of each row, and cope with a row that has no tags.

Your working space Next.js · 8 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; import Tests from "./Tests.jsx"; export default function Page() { return ( <main> <h1>Reset Shared State Between Tests</h1> <Tests /> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } import "@/tests/fixture.test.js"; import { runTests } from "@/lib/test.js"; export default async function Tests() { const results = await runTests(); return ( <section> <h2>Tests in tests/fixture.test.js</h2> <p> Tests: {results.filter((r) => r.pass).length}/{results.length} passed </p> <ul> {results.map((r) => ( <li key={r.name} className={r.pass ? "pass" : "fail"}> {r.pass ? "✓" : "✗"} {r.name} {r.message && `: ${r.message}`} </li> ))} </ul> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run(seed) { return seed.map((row) => ({ ...row })); } export const examples = [ [[{ id: 1, title: "Routing" }], [{ id: 1, title: "Routing" }]], ]; // A tiny stand-in for node:test and node:assert/strict, so tests can run in // the browser. On your computer, write instead: // import { test } from "node:test"; // import assert from "node:assert/strict"; const tests = []; export function test(name, fn) { tests.push({ name, fn }); } const show = (value) => JSON.stringify(value) ?? String(value); export const assert = { equal(actual, expected) { if (!Object.is(actual, expected)) throw new Error(`expected ${show(expected)}, got ${show(actual)}`); }, deepEqual(actual, expected) { if (show(actual) !== show(expected)) throw new Error(`expected ${show(expected)}, got ${show(actual)}`); }, }; export async function runTests() { const results = []; for (const { name, fn } of tests) { try { await fn(); results.push({ name, pass: true, message: "" }); } catch (error) { results.push({ name, pass: false, message: error.message }); } } return results; } import { test, assert } from "@/lib/test.js"; import { run } from "@/lib/contract.js"; test("changing a copied row leaves the seed alone", () => { const seed = [{ id: 1, title: "Routing" }]; const rows = run(seed); rows[0].title = "Changed"; assert.deepEqual(seed, [{ id: 1, title: "Routing" }]); }); test("changing a copied row's tags leaves the seed's tags alone", () => { const seed = [{ id: 1, tags: ["react"] }]; const rows = run(seed); rows[0].tags.push("changed"); assert.deepEqual(seed, [{ id: 1, tags: ["react"] }]); });
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

Name the nested value that must not be shared, and give each copy its own. This isn't a general deep-clone recipe: you're copying exactly what tests can change.

Hint 2: a first step

Inside the object you build for each row, after ...row, give tags a value of its own: a new array with the same items. Run the tests, then try a seed row without tags: does run still work?

Show one solution
JavaScript
export function run(seed) {
  return seed.map((row) => (row.tags ? { ...row, tags: [...row.tags] } : { ...row }));
}

tags comes after ...row, so it replaces the shared array with a new one holding the same strings; strings can't be changed, so copying one level more is enough. A row without tags is copied as before, rather than gaining an empty tags it never had, so the case table's original row still matches. structuredClone(seed) would also pass, and copies everything, which is fine for plain data but hides which part actually needed copying.

Explain it without the code

The capstone project's repository is created by a function rather than being a single module-level object. Write one sentence on how that helps its tests.

Going further

Node's test runner has beforeEach, which runs before every test: a good place to build a fresh fixture. See the test runner documentation.

Was this article helpful?

Your response is saved on this device.