Skip to content

Testing Contracts

The Course
•
16 min study

A useful test can explain its failure

Keep the beginner assertion pattern: compare actual with expected and throw on mismatch. Add a label that identifies the case. A test should say what the caller needs, not merely repeat the implementation in a second spelling.

For an update, verify changed output, unchanged input, a missing id, and an empty list. For a decoder, verify malformed fields and duplicates. When a test claims to protect a rule, temporarily break that rule and watch the check fail. This is a small mutation experiment: it proves sensitivity to one particular defect, not complete correctness.

Array and object equality compares identity. To check a specific field, assert that field. For a whole structured result you can use a test framework's deep comparison once you move to the downloaded Node project. JSON string comparisons are acceptable only when your test deliberately assumes JSON-compatible values and property ordering; they are not universal equality.

Keep tests repeatable. They should create their own inputs rather than depend on a previous run's globals. We will use deferred promises later to control async order without guessing how many milliseconds a machine needs.

Predict and trace

Write the output before running. Follow the values through each call; if your prediction differs, identify the first step that surprised you.

Predict, then run JavaScript
function assertEqual(actual, expected, label) {
  if (actual !== expected) {
    throw new Error(label);
  }
}

function rename(book, title) {
  return { ...book, title };
}

const before = { id: "js", title: "Old" };
const after = rename(before, "New");

assertEqual(after.title, "New", "new title");
assertEqual(before.title, "Old", "input unchanged");
console.log("2 checks passed");
Check your prediction
Text
2 checks passed

A mutating rename can produce the right new title but fails the unchanged-input assertion.

Keep the assertion outside the operation catch

A test can accidentally catch its own failure and report success. This happens when an assertion expecting rejection is placed in the same try block as the operation. Capture whether the operation failed, then make the assertion after the catch.

Use distinguishable fixtures. For nonmutation, an original with two records and different values can reveal accidental replacement or mutation that a single record would hide. A regression test should fail for a deliberate implementation defect, not just for a syntax error.

Keep the assertion outside the operation catch: trace JavaScript
function didThrow(work) {
  let rejected = false;

  try {
    work();
  } catch {
    rejected = true;
  }

  return rejected;
}

console.log(
  didThrow(() => {
    throw new Error("expected");
  })
);
console.log(didThrow(() => 1));
Check your prediction
Text
true
false

The helper reports only the operation outcome. Throwing an assertion inside that try would mix test failure with the failure the test was trying to detect.

Keep the assertion outside the operation catch: contrast JavaScript
const before = [
  { id: "a", title: "Old" },
  { id: "b", title: "Keep" }
];
const after = before.map(book =>
  book.id === "a" ? { ...book, title: "New" } : book
);

if (before[0].title !== "Old" || after[1].title !== "Keep") {
  throw new Error("Contract broken");
}

console.log("input and unrelated row preserved");
Check your prediction
Text
input and unrelated row preserved

A returned New title alone would not prove preservation. This assertion also checks the previous state and a row outside the requested update.

Try the rule on new inputs

Change the update to mutate the matching source row and confirm the preservation assertion fails. For an expected-throw test, first run a callback that does not throw to prove your test cannot accept success by accident.

Build it yourself

Exercise

Prove an update contract

retitle(books, id, title) returns a new array in which one book has a new title. Its contract has four rules: the matching book gets the new title, other books are kept, the input array and its records are not changed, and an unknown id throws. Fill in checkRetitle(update) with one labelled check per rule. The program runs your checks against the correct retitle and against retitleInPlace, a deliberate defect that edits the record in place. Your checks pass only if they catch the defect by name:

Text
retitle: passed
retitleInPlace: FAILED input unchanged
Your working space JavaScript
function didThrow(action) {
  try {
    action();
  } catch {
    return true;
  }
  return false;
}

function retitle(books, id, title) {
  if (!books.some(book => book.id === id)) {
    throw new Error(`Unknown book: ${id}`);
  }
  return books.map(book => (book.id === id ? { ...book, title } : book));
}

// A deliberate defect: edits the matching record in place.
function retitleInPlace(books, id, title) {
  const book = books.find(item => item.id === id);
  if (!book) {
    throw new Error(`Unknown book: ${id}`);
  }
  book.title = title;
  return [...books];
}

function checkRetitle(update) {
  const failures = [];
  const check = (passed, label) => {
    if (!passed) failures.push(label);
  };
  // Build fresh books, call update once, then add one labelled check per rule.
  return failures;
}

for (const [name, update] of [["retitle", retitle], ["retitleInPlace", retitleInPlace]]) {
  const failures = checkRetitle(update);
  console.log(`${name}: ${failures.length === 0 ? "passed" : "FAILED " + failures.join(", ")}`);
}
Hint 1: the idea

Each check compares one observable fact with what the contract promises. The defect returns the right new title, so a check on the output alone cannot catch it; one check has to look at the array you passed in, after the call.

Hint 2: a first step

Inside checkRetitle, create two books with different titles, store the result of update(before, "a", "New"), and add check(after[0].title === "New", "changed title"). Run: both versions print passed, which shows that this check alone cannot see the bug.

Show one solution
JavaScript
function didThrow(action) {
  try {
    action();
  } catch {
    return true;
  }
  return false;
}

function retitle(books, id, title) {
  if (!books.some(book => book.id === id)) {
    throw new Error(`Unknown book: ${id}`);
  }
  return books.map(book => (book.id === id ? { ...book, title } : book));
}

// A deliberate defect: edits the matching record in place.
function retitleInPlace(books, id, title) {
  const book = books.find(item => item.id === id);
  if (!book) {
    throw new Error(`Unknown book: ${id}`);
  }
  book.title = title;
  return [...books];
}

function checkRetitle(update) {
  const failures = [];
  const check = (passed, label) => {
    if (!passed) failures.push(label);
  };
  const before = [
    { id: "a", title: "Old" },
    { id: "b", title: "Keep" }
  ];
  const after = update(before, "a", "New");

  check(after[0].title === "New", "changed title");
  check(after[1].title === "Keep", "other book kept");
  check(before[0].title === "Old", "input unchanged");
  check(didThrow(() => update(before, "zzz", "New")), "missing id throws");
  return failures;
}

for (const [name, update] of [["retitle", retitle], ["retitleInPlace", retitleInPlace]]) {
  const failures = checkRetitle(update);
  console.log(`${name}: ${failures.length === 0 ? "passed" : "FAILED " + failures.join(", ")}`);
}
Text
retitle: passed
retitleInPlace: FAILED input unchanged

retitleInPlace gets every output right: the new title, the kept book, and the thrown error. Only before[0].title === "Old" looks at the caller's data after the call, so it is the one check that names the defect. The fixtures need two books with different titles, or "other book kept" could pass by accident. The missing-id check uses didThrow and asserts on its result outside the try, so a thrown assertion can never be mistaken for the expected rejection. Running the same checks against a known-bad version is the mutation experiment from the top of the lesson: it shows these checks are sensitive to that defect.

Explain before moving on

Why is a function passed to didThrow instead of its result? Which of your four checks would still pass if retitle returned the input array unchanged?

Was this article helpful?

Your response is saved on this device.