Skip to content

Test the Rejected Operation Too

The Course
•
18 min study

The decision

A service’s guarantees live in the cases where it refuses to act. Test another owner, an expired session, a stale version and an invalid batch, including what must remain unchanged.

Read, predict, run

The model selects which operations a small policy matrix allows: an operation goes ahead only when every condition holds.

JavaScript
export function run(cases) {
  return cases
    .filter(
      (item) => item.authenticated && item.authorized && item.versionMatches,
    )
    .map((item) => item.name);
}

Before pressing Run, predict what run returns for [{"name": "stale", "authenticated": true, "authorized": true, "versionMatches": false}, {"name": "valid", "authenticated": true, "authorized": true, "versionMatches": true}], from the code above. Write your answers down first: after Run, the case table shows the expected values beside the actual ones.

Test the Rejected Operation Too Next.js · 9 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; import Tests from "./Tests.jsx"; export default function Page() { return ( <main> <h1>Test the Rejected Operation Too</h1> <Tests /> <p>lib/contract.js: which operations the policy allows.</p> <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/edit.test.js"; import { runTests } from "@/lib/test.js"; export default async function Tests() { const results = await runTests(); return ( <section> <h2>Tests in tests/edit.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(cases) { return cases .filter( (item) => item.authenticated && item.authorized && item.versionMatches, ) .map((item) => item.name); } export const examples = [ [ [ { name: "stale", authenticated: true, authorized: true, versionMatches: false, }, { name: "valid", authenticated: true, authorized: true, versionMatches: true, }, ], ["valid"], ], ]; // A small review service. Each call to createService gets its own rows, so // tests can't change each other's starting point. export function createService(seed) { const rows = structuredClone(seed); return { rows: () => rows, edit(actor, id, { title, version }) { const row = rows.find((item) => item.id === id); if (!row || row.ownerId !== actor?.id) { return { ok: false, code: "not_found" }; } row.title = title; if (row.version !== version) return { ok: false, code: "conflict" }; row.version += 1; return { ok: true, version: row.version }; }, }; } // 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 { createService } from "@/lib/service.js"; const seed = [{ id: 1, ownerId: "ada", title: "Draft", version: 2 }]; test("an edit from the owner at the current version saves", () => { const service = createService(seed); const result = service.edit({ id: "ada" }, 1, { title: "Final", version: 2 }); assert.deepEqual(result, { ok: true, version: 3 }); }); test("another owner's edit is refused", () => { const service = createService(seed); const result = service.edit({ id: "grace" }, 1, { title: "Grace was here", version: 2 }); assert.deepEqual(result, { ok: false, code: "not_found" }); }); test("a stale edit is refused", () => { const service = createService(seed); const result = service.edit({ id: "ada" }, 1, { title: "Late", version: 1 }); assert.deepEqual(result, { ok: false, code: "conflict" }); });
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
  • Input [{"name": "stale", "authenticated": true, "authorized": true, "versionMatches": false}, {"name": "valid", "authenticated": true, "authorized": true, "versionMatches": true}] → ["valid"].

The case table computes these results on the server side of the simulation. It compares values; it does not prove a production deployment or database works.

A refusal that still writes

A policy matrix says which operations should be refused. A test of the real service must check that a refused operation really changed nothing. The lab's lib/service.js has an edit with a bug that a refactor could easily introduce, an assignment one line too early:

JavaScript
edit(actor, id, { title, version }) {
  const row = rows.find((item) => item.id === id);
  if (!row || row.ownerId !== actor?.id) {
    return { ok: false, code: "not_found" };
  }
  row.title = title;
  if (row.version !== version) return { ok: false, code: "conflict" };
  row.version += 1;
  return { ok: true, version: row.version };
},

tests/edit.test.js has three tests, written in the same small runner as the intermediate course, shaped like node:test. One of them:

JavaScript
test("a stale edit is refused", () => {
  const service = createService(seed);
  const result = service.edit({ id: "ada" }, 1, { title: "Late", version: 1 });
  assert.deepEqual(result, { ok: false, code: "conflict" });
});

Predict how many of the three tests pass against this buggy edit.

Three tests and a buggy service Next.js · 9 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; import Tests from "./Tests.jsx"; export default function Page() { return ( <main> <h1>Test the Rejected Operation Too</h1> <Tests /> <p>lib/contract.js: which operations the policy allows.</p> <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/edit.test.js"; import { runTests } from "@/lib/test.js"; export default async function Tests() { const results = await runTests(); return ( <section> <h2>Tests in tests/edit.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(cases) { return cases .filter( (item) => item.authenticated && item.authorized && item.versionMatches, ) .map((item) => item.name); } export const examples = [ [ [ { name: "stale", authenticated: true, authorized: true, versionMatches: false, }, { name: "valid", authenticated: true, authorized: true, versionMatches: true, }, ], ["valid"], ], ]; // A small review service. Each call to createService gets its own rows, so // tests can't change each other's starting point. export function createService(seed) { const rows = structuredClone(seed); return { rows: () => rows, edit(actor, id, { title, version }) { const row = rows.find((item) => item.id === id); if (!row || row.ownerId !== actor?.id) { return { ok: false, code: "not_found" }; } row.title = title; if (row.version !== version) return { ok: false, code: "conflict" }; row.version += 1; return { ok: true, version: row.version }; }, }; } // 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 { createService } from "@/lib/service.js"; const seed = [{ id: 1, ownerId: "ada", title: "Draft", version: 2 }]; test("an edit from the owner at the current version saves", () => { const service = createService(seed); const result = service.edit({ id: "ada" }, 1, { title: "Final", version: 2 }); assert.deepEqual(result, { ok: true, version: 3 }); }); test("another owner's edit is refused", () => { const service = createService(seed); const result = service.edit({ id: "grace" }, 1, { title: "Grace was here", version: 2 }); assert.deepEqual(result, { ok: false, code: "not_found" }); }); test("a stale edit is refused", () => { const service = createService(seed); const result = service.edit({ id: "ada" }, 1, { title: "Late", version: 1 }); assert.deepEqual(result, { ok: false, code: "conflict" }); });
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

All three: Tests: 3/3 passed. The stale edit does return conflict, so the test is satisfied, but by then the row's title is already Late. The page showing that row would display a title nobody saved successfully, and a later edit at version 2 would keep it. A test that checks only the answer can't see this.

The failure to avoid

An assertion that an error was returned is incomplete if a write already happened. For every rejected operation, take a copy of the state before the call and compare after it. structuredClone makes the copy deep, so the comparison can't be fooled by the service changing an object the copy shares.

Exercise

Catch the write, then fix it

  1. In tests/edit.test.js, add a test named a stale edit changes nothing. Take a snapshot of service.rows() before the stale edit, then assert both the conflict result and that the rows still equal the snapshot.
  2. Run. Your new test must fail against the current service; if it passes, it can't detect the bug.
  3. Fix edit in lib/service.js so all four tests pass.
Your working space Next.js · 9 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; import Tests from "./Tests.jsx"; export default function Page() { return ( <main> <h1>Test the Rejected Operation Too</h1> <Tests /> <p>lib/contract.js: which operations the policy allows.</p> <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/edit.test.js"; import { runTests } from "@/lib/test.js"; export default async function Tests() { const results = await runTests(); return ( <section> <h2>Tests in tests/edit.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(cases) { return cases .filter( (item) => item.authenticated && item.authorized && item.versionMatches, ) .map((item) => item.name); } export const examples = [ [ [ { name: "stale", authenticated: true, authorized: true, versionMatches: false, }, { name: "valid", authenticated: true, authorized: true, versionMatches: true, }, ], ["valid"], ], ]; // A small review service. Each call to createService gets its own rows, so // tests can't change each other's starting point. export function createService(seed) { const rows = structuredClone(seed); return { rows: () => rows, edit(actor, id, { title, version }) { const row = rows.find((item) => item.id === id); if (!row || row.ownerId !== actor?.id) { return { ok: false, code: "not_found" }; } row.title = title; if (row.version !== version) return { ok: false, code: "conflict" }; row.version += 1; return { ok: true, version: row.version }; }, }; } // 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 { createService } from "@/lib/service.js"; const seed = [{ id: 1, ownerId: "ada", title: "Draft", version: 2 }]; test("an edit from the owner at the current version saves", () => { const service = createService(seed); const result = service.edit({ id: "ada" }, 1, { title: "Final", version: 2 }); assert.deepEqual(result, { ok: true, version: 3 }); }); test("another owner's edit is refused", () => { const service = createService(seed); const result = service.edit({ id: "grace" }, 1, { title: "Grace was here", version: 2 }); assert.deepEqual(result, { ok: false, code: "not_found" }); }); test("a stale edit is refused", () => { const service = createService(seed); const result = service.edit({ id: "ada" }, 1, { title: "Late", version: 1 }); assert.deepEqual(result, { ok: false, code: "conflict" }); });
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

A rejected operation has two outcomes to check: what the caller is told, and what's stored. The snapshot has to be a copy taken before the call, or it changes along with the rows.

Hint 2: a first step

Copy a stale edit is refused. Before the service.edit line, add const before = structuredClone(service.rows());. After the existing assertion, compare service.rows() with before. Run, and read the failure message: it names the title that shouldn't be there.

Show one solution

In tests/edit.test.js:

JavaScript
test("a stale edit changes nothing", () => {
  const service = createService(seed);
  const before = structuredClone(service.rows());
  const result = service.edit({ id: "ada" }, 1, { title: "Late", version: 1 });
  assert.deepEqual(result, { ok: false, code: "conflict" });
  assert.deepEqual(service.rows(), before);
});

Against the buggy service it fails with expected [{"id":1,"ownerId":"ada","title":"Draft","version":2}], got [{"id":1,"ownerId":"ada","title":"Late","version":2}]. In lib/service.js, every check comes before any write:

JavaScript
if (row.version !== version) return { ok: false, code: "conflict" };
row.title = title;
row.version += 1;

Now Tests: 4/4 passed. Without structuredClone, before would be the same array as the rows, the buggy write would change both, and the test would pass. The same snapshot belongs in the other-owner test too: the policy matrix lists four kinds of refusal, and each one deserves its own "changes nothing" test.

Explain it without the code

Write the four rejected operations you'd test first for the Review Queue, and the state each must leave unchanged.

Going further

In the downloadable capstone, tests/ runs the same kind of snapshot test against the real SQLite repository with node --test. Read the Next.js testing guide for browser-level tests. The preview runs code-playpad's Next.js simulation. Real caching, hydration, authentication and persistence require the real-server checks described on Day 7.

Was this article helpful?

Your response is saved on this device.