Skip to content

Checkpoint: Regression Evidence

The Course
•
25 min study

A checkpoint for testing should test your tests. You are given a small helper, firstSuccess(tasks), and three mutants of it, each a one-line change someone could plausibly make. Think of a fallback chain: try the main server, then a mirror, then a backup. Your job is to write the suite: it must pass the real helper and fail every mutant, and each failure should say which part of the contract broke.

The contract: firstSuccess calls each function in tasks in order, one at a time. It fulfils with the first success and calls nothing after that. If every task fails, it rejects with the last reason, whatever that value is, including undefined. A task may throw synchronously instead of returning a rejected promise. An empty list is a RangeError.

This uses all three Day 5 lessons: hostile collaborators to produce the awkward failures, identity checks on rejection reasons, and mutation checking to show that each assertion is doing work.

Predict, run, and explain

Write the output and trace the important state changes before checking it. Then run the program. Each editor is independent. Async examples end with main() so this editor waits for their work.

Predict, then run JavaScript
async function main() {
  async function run(task) {
    return await task();
  }

  const outcome = await run(() => {
    throw "sync";
  }).then(
    value => `fulfilled: ${value}`,
    reason => `rejected: ${reason}`
  );

  console.log(outcome);
}

main();
Check your prediction
Text
rejected: sync

The task threw before returning anything, but the throw happened inside an async function, so the caller sees an ordinary rejection. Your suite can therefore use synchronous throws as hostile tasks and still observe them through await.

Acceptance cases before you code

Write a small test plan before implementing distinguishing regression evidence. These cases extend the brief; they are not a second worked solution. Predict the expected behavior independently, then test through the public function. A good ordinary example and a good boundary example should catch different possible mistakes.

Case to tryWhat your result should demonstrate
Two sources throw, the third succeedsFulfils with the third's value after exactly 3 calls
Every source rejects with a different ErrorRejects with the last one, compared by identity
The only source rejects with undefinedStill rejects; it must not fulfil
The first source succeedsExactly one call

After the core task passes, deliberately break one rule and identify the case that notices it. Restore the implementation and explain the failure in terms of the contract, not the number of assertions. If a case requires a concept you have not recalled, revisit the relevant lesson before opening the solution.

Your turn

Exercise

Checkpoint: a suite that kills three mutants

firstSuccess and its three mutants are supplied; do not change them. Write suite(firstSuccessFn) so it covers the four acceptance cases and returns pass or FAIL (reason) for the first check that fails. Print:

Text
firstSuccess: pass
skips last:   FAIL (success from the last source)
keeps first:  FAIL (rejection reason)
truthy check: FAIL (undefined rejection)
Your workspace JavaScript
async function main() {
  // The helper under test: try each source in order, one at a time.
  // Fulfils with the first success; otherwise rejects with the LAST reason.
  async function firstSuccess(tasks) {
    if (tasks.length === 0) throw new RangeError("no tasks");
    let last;
    for (const task of tasks) {
      try {
        return await task();
      } catch (reason) {
        last = reason;
      }
    }
    throw last;
  }

  // Three plausible mutants.
  async function skipsLast(tasks) {
    if (tasks.length === 0) throw new RangeError("no tasks");
    let last;
    for (const task of tasks.slice(0, -1)) {
      try {
        return await task();
      } catch (reason) {
        last = reason;
      }
    }
    throw last;
  }
  async function keepsFirst(tasks) {
    if (tasks.length === 0) throw new RangeError("no tasks");
    let failed = false;
    let first;
    for (const task of tasks) {
      try {
        return await task();
      } catch (reason) {
        if (!failed) first = reason;
        failed = true;
      }
    }
    throw first;
  }
  async function truthyCheck(tasks) {
    if (tasks.length === 0) throw new RangeError("no tasks");
    let last;
    for (const task of tasks) {
      try {
        return await task();
      } catch (reason) {
        last = reason;
      }
    }
    if (last) throw last;
  }

  async function settle(run) {
    try {
      return { ok: true, value: await run() };
    } catch (reason) {
      return { ok: false, reason };
    }
  }

  async function suite(firstSuccessFn) {
    // Use hostile tasks (synchronous throws, undefined rejections,
    // success only from a later source) and count calls. Return "pass"
    // or "FAIL (what broke)" for the first check that fails.
    return "pass";
  }

  console.log(`firstSuccess: ${await suite(firstSuccess)}`);
  console.log(`skips last:   ${await suite(skipsLast)}`);
  console.log(`keeps first:  ${await suite(keepsFirst)}`);
  console.log(`truthy check: ${await suite(truthyCheck)}`);
}

main();
Hint 1: the idea

Each mutant breaks a different rule, so each needs a check that only that rule's violation can fail. Ask, for each mutant, what input would make it behave differently from firstSuccess. Then make sure your check can see that difference: a call count, a reason compared by ===, or whether the result fulfilled at all.

Hint 2: a first step

Add the settle pattern for each case, so a rejection becomes a value you can inspect. Start with case 1: two tasks that throw and a third that returns "backup", all incrementing a calls counter. Run it: skips last should already fail. Then add the cases for the other two mutants.

Show one solution
JavaScript
async function main() {
  // The helper under test: try each source in order, one at a time.
  // Fulfils with the first success; otherwise rejects with the LAST reason.
  async function firstSuccess(tasks) {
    if (tasks.length === 0) throw new RangeError("no tasks");
    let last;
    for (const task of tasks) {
      try {
        return await task();
      } catch (reason) {
        last = reason;
      }
    }
    throw last;
  }

  // Three plausible mutants.
  async function skipsLast(tasks) {
    if (tasks.length === 0) throw new RangeError("no tasks");
    let last;
    for (const task of tasks.slice(0, -1)) {
      try {
        return await task();
      } catch (reason) {
        last = reason;
      }
    }
    throw last;
  }
  async function keepsFirst(tasks) {
    if (tasks.length === 0) throw new RangeError("no tasks");
    let failed = false;
    let first;
    for (const task of tasks) {
      try {
        return await task();
      } catch (reason) {
        if (!failed) first = reason;
        failed = true;
      }
    }
    throw first;
  }
  async function truthyCheck(tasks) {
    if (tasks.length === 0) throw new RangeError("no tasks");
    let last;
    for (const task of tasks) {
      try {
        return await task();
      } catch (reason) {
        last = reason;
      }
    }
    if (last) throw last;
  }

  async function settle(run) {
    try {
      return { ok: true, value: await run() };
    } catch (reason) {
      return { ok: false, reason };
    }
  }

  async function suite(firstSuccessFn) {
    // 1. Only the last of three sources works.
    let calls = 0;
    const failing = name => () => {
      calls += 1;
      throw new Error(`${name} down`); // synchronous throw
    };
    const last = await settle(() =>
      firstSuccessFn([failing("main"), failing("mirror"), async () => {
        calls += 1;
        return "backup";
      }])
    );
    if (!last.ok || last.value !== "backup" || calls !== 3) return "FAIL (success from the last source)";

    // 2. Every source fails: the last reason wins, by identity.
    const reasons = [new Error("a"), new Error("b")];
    const all = await settle(() => firstSuccessFn(reasons.map(r => () => Promise.reject(r))));
    if (all.ok || all.reason !== reasons[1]) return "FAIL (rejection reason)";

    // 3. A rejection with undefined is still a failure.
    const quiet = await settle(() => firstSuccessFn([() => Promise.reject(undefined)]));
    if (quiet.ok) return "FAIL (undefined rejection)";

    // 4. No source is called after a success.
    calls = 0;
    const count = async () => {
      calls += 1;
      return "ok";
    };
    await settle(() => firstSuccessFn([count, count, count]));
    if (calls !== 1) return "FAIL (called after success)";

    return "pass";
  }

  console.log(`firstSuccess: ${await suite(firstSuccess)}`);
  console.log(`skips last:   ${await suite(skipsLast)}`);
  console.log(`keeps first:  ${await suite(keepsFirst)}`);
  console.log(`truthy check: ${await suite(truthyCheck)}`);
}

main();
Text
firstSuccess: pass
skips last:   FAIL (success from the last source)
keeps first:  FAIL (rejection reason)
truthy check: FAIL (undefined rejection)

Case 1 needs success from the last source: that is the only input where skipping the final task gives a different answer. Its synchronous throws also show that firstSuccess treats them like rejections. Case 2 uses two distinct Error objects and compares with ===, so keepsFirst fails even though it does reject. Case 3 rejects with undefined, which truthyCheck mistakes for "no failure" and fulfils. Case 4 kills no mutant here, but it guards the "nothing after success" rule against a future change. That is why the suite reports which rule broke, not just that something did.

Change it and test it

Write a fourth mutant that your suite does not catch, for example one that never calls a fourth source. Add the smallest check that kills it. Then remove each of your checks in turn and confirm that some mutant survives each removal: a check that no mutant needs is either redundant or guarding a rule no mutant breaks yet.

Was this article helpful?

Your response is saved on this device.