Skip to content

Tests & Failure Lab

The Course
•
15 min study

The project's pool.test.js is part of the course, not decoration. It verifies bounded starts and ordered results using explicit gates, first-failure behavior while a peer is held, cancellation before and during work, invalid limits, source errors, cleanup and undefined causes.

Everything in this lesson runs in the page. If you also want to run the downloaded suite with npm test, the setup is in Modules & Local Use, the next lesson; it is optional. In that suite, Node's built-in test(name, callback) groups each case; assert.deepEqual compares complete values and assert.rejects checks awaited failures. These are the same contract ideas practiced in the console helpers, with a standard reporting tool.

Mutate only one behavior at a time. Replace indexed assignment with push, skip iterator.return, or remove the no-new-work guard. The appropriate test should fail. The section below does this in the page, with a switch that plants each bug for you. Restore the source before continuing. A test that fails for a syntax error does not prove it detects the behavioral defect; the mutation should remain a runnable program.

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() {
  let release;
  const gate = new Promise(resolve => {
    release = resolve;
  });
  let settled = false;
  const work = gate.then(() => {
    settled = true;
  });

  console.log(settled);
  release();
  await work;
  console.log(settled);
}

main();
Check your prediction
Text
false
true

Match a test to the guarantee it distinguishes

A result-order mutation needs reverse completion; a cleanup mutation needs an unfinished iterator; a start-guard mutation needs more work available after failure. Ordinary completion cannot distinguish all three. Read fixtures as controlled collaborators that expose public behavior, not as snapshots of private implementation details.

Boundary or caseWhat to inspect
Bounded startsObserve peak work and refill before a held peer completes
First failureObserve source closure and no new pulls while peers settle
External signalPreserve caller reason and release its listener

Predict the failed assertion before changing the maintained implementation. If your change causes a syntax error or hangs, that is not evidence of the intended regression test. Restore source, confirm the baseline, and only then try another mutation.

Run the mutation lab in the page

mapLimit below is a reduced pool: no signal, no validation, but the same worker loop, failure flag and iterator cleanup. Its fourth argument plants one bug: "push" records results in completion order, "no-return" skips closing an unfinished source, and "no-guard" lets workers keep starting items after a failure. Two tests run against all four variants. Predict which cells say FAIL.

Three planted bugs, two tests JavaScript
async function main() {
  // A reduced pool with a switch that plants one known bug at a time.
  async function mapLimit(items, mapper, limit, mutant = "none") {
    const iterator = items[Symbol.iterator]();
    const results = [];
    let next = 0;
    let exhausted = false;
    let failed = false;
    let failure;

    async function worker() {
      while ((mutant === "no-guard" || !failed) && !exhausted) {
        const step = iterator.next();
        if (step.done) {
          exhausted = true;
          return;
        }
        const index = next++;
        try {
          const value = await mapper(step.value, index);
          if (mutant === "push") results.push(value);
          else results[index] = value;
        } catch (error) {
          if (!failed) {
            failed = true;
            failure = error;
          }
        }
      }
    }

    try {
      await Promise.all(Array.from({ length: limit }, () => worker()));
    } finally {
      if (!exhausted && mutant !== "no-return") iterator.return?.();
    }
    if (failed) throw failure;
    return results;
  }

  function deferred() {
    let resolve;
    const promise = new Promise(yes => {
      resolve = yes;
    });
    return { promise, resolve };
  }

  // Each test returns true (pass) or false (fail) for one variant.
  async function orderTest(mutant) {
    const gates = [deferred(), deferred(), deferred()];
    const work = mapLimit([0, 1, 2], async n => {
      await gates[n].promise;
      return n * 10;
    }, 3, mutant);
    gates[2].resolve();
    gates[1].resolve();
    gates[0].resolve();
    return (await work).join() === "0,10,20";
  }

  async function cleanupTest(mutant) {
    let closed = false;
    function* source() {
      try {
        yield 0;
        yield 1;
        yield 2;
      } finally {
        closed = true;
      }
    }
    await mapLimit(source(), async n => {
      if (n === 0) throw new Error("first fails");
      return n;
    }, 1, mutant).catch(() => {});
    return closed;
  }

  const tests = { order: orderTest, cleanup: cleanupTest };
  for (const mutant of ["none", "push", "no-return", "no-guard"]) {
    const row = [];
    for (const [name, check] of Object.entries(tests)) {
      row.push(`${name} ${(await check(mutant)) ? "pass" : "FAIL"}`);
    }
    console.log(`${mutant.padEnd(9)} | ${row.join(" | ")}`);
  }
}

main();
Check your prediction
Text
none      | order pass | cleanup pass
push      | order FAIL | cleanup pass
no-return | order pass | cleanup FAIL
no-guard  | order pass | cleanup pass

Each row is one variant of the pool; each column is one test. push fails only the order test, because only that test finishes jobs out of order. no-return fails only the cleanup test, the only one whose source is left unfinished. no-guard passes both, and that is the useful finding: removing the "stop after a failure" guard is a real bug (the pool keeps calling the mapper after it has decided to reject), but neither test can see it. The cleanup test does not notice either, because the mutant keeps pulling until the generator is exhausted, and exhaustion runs finally too. A surviving mutant means a missing test, not a correct pool.

Your turn

Exercise

Write the test that kills the survivor

Add noNewStartsTest(mutant) to the lab. It should pass for the correct pool and fail for the no-guard variant, without changing the pool. Keep it independent of timing: no timers and no guessed delays. Print:

Text
none      | order pass | cleanup pass | no new starts pass
push      | order FAIL | cleanup pass | no new starts pass
no-return | order pass | cleanup FAIL | no new starts pass
no-guard  | order pass | cleanup pass | no new starts FAIL
Your workspace JavaScript
async function main() {
  // A reduced pool with a switch that plants one known bug at a time.
  async function mapLimit(items, mapper, limit, mutant = "none") {
    const iterator = items[Symbol.iterator]();
    const results = [];
    let next = 0;
    let exhausted = false;
    let failed = false;
    let failure;

    async function worker() {
      while ((mutant === "no-guard" || !failed) && !exhausted) {
        const step = iterator.next();
        if (step.done) {
          exhausted = true;
          return;
        }
        const index = next++;
        try {
          const value = await mapper(step.value, index);
          if (mutant === "push") results.push(value);
          else results[index] = value;
        } catch (error) {
          if (!failed) {
            failed = true;
            failure = error;
          }
        }
      }
    }

    try {
      await Promise.all(Array.from({ length: limit }, () => worker()));
    } finally {
      if (!exhausted && mutant !== "no-return") iterator.return?.();
    }
    if (failed) throw failure;
    return results;
  }

  function deferred() {
    let resolve;
    const promise = new Promise(yes => {
      resolve = yes;
    });
    return { promise, resolve };
  }

  // Each test returns true (pass) or false (fail) for one variant.
  async function orderTest(mutant) {
    const gates = [deferred(), deferred(), deferred()];
    const work = mapLimit([0, 1, 2], async n => {
      await gates[n].promise;
      return n * 10;
    }, 3, mutant);
    gates[2].resolve();
    gates[1].resolve();
    gates[0].resolve();
    return (await work).join() === "0,10,20";
  }

  async function cleanupTest(mutant) {
    let closed = false;
    function* source() {
      try {
        yield 0;
        yield 1;
        yield 2;
      } finally {
        closed = true;
      }
    }
    await mapLimit(source(), async n => {
      if (n === 0) throw new Error("first fails");
      return n;
    }, 1, mutant).catch(() => {});
    return closed;
  }

  async function noNewStartsTest(mutant) {
    // Return true only if no item starts after the first failure.
    return true;
  }

  const tests = { order: orderTest, cleanup: cleanupTest, "no new starts": noNewStartsTest };
  for (const mutant of ["none", "push", "no-return", "no-guard"]) {
    const row = [];
    for (const [name, check] of Object.entries(tests)) {
      row.push(`${name} ${(await check(mutant)) ? "pass" : "FAIL"}`);
    }
    console.log(`${mutant.padEnd(9)} | ${row.join(" | ")}`);
  }
}

main();
Hint 1: the idea

The guard's job is about the mapper, not about results or cleanup: after the first failure, no new item should start. So the test has to record which items started, in a situation where there is still more input left when the first failure happens.

Hint 2: a first step

Use limit 1, so starts are strictly one after another, and a source of three items where the first one fails. Record each value the mapper receives. Then decide what the list should contain for the correct pool before writing the comparison.

Show one solution
JavaScript
async function main() {
  // A reduced pool with a switch that plants one known bug at a time.
  async function mapLimit(items, mapper, limit, mutant = "none") {
    const iterator = items[Symbol.iterator]();
    const results = [];
    let next = 0;
    let exhausted = false;
    let failed = false;
    let failure;

    async function worker() {
      while ((mutant === "no-guard" || !failed) && !exhausted) {
        const step = iterator.next();
        if (step.done) {
          exhausted = true;
          return;
        }
        const index = next++;
        try {
          const value = await mapper(step.value, index);
          if (mutant === "push") results.push(value);
          else results[index] = value;
        } catch (error) {
          if (!failed) {
            failed = true;
            failure = error;
          }
        }
      }
    }

    try {
      await Promise.all(Array.from({ length: limit }, () => worker()));
    } finally {
      if (!exhausted && mutant !== "no-return") iterator.return?.();
    }
    if (failed) throw failure;
    return results;
  }

  function deferred() {
    let resolve;
    const promise = new Promise(yes => {
      resolve = yes;
    });
    return { promise, resolve };
  }

  // Each test returns true (pass) or false (fail) for one variant.
  async function orderTest(mutant) {
    const gates = [deferred(), deferred(), deferred()];
    const work = mapLimit([0, 1, 2], async n => {
      await gates[n].promise;
      return n * 10;
    }, 3, mutant);
    gates[2].resolve();
    gates[1].resolve();
    gates[0].resolve();
    return (await work).join() === "0,10,20";
  }

  async function cleanupTest(mutant) {
    let closed = false;
    function* source() {
      try {
        yield 0;
        yield 1;
        yield 2;
      } finally {
        closed = true;
      }
    }
    await mapLimit(source(), async n => {
      if (n === 0) throw new Error("first fails");
      return n;
    }, 1, mutant).catch(() => {});
    return closed;
  }

  async function noNewStartsTest(mutant) {
    const started = [];
    await mapLimit([0, 1, 2], async n => {
      started.push(n);
      if (n === 0) throw new Error("first fails");
      return n;
    }, 1, mutant).catch(() => {});
    return started.join() === "0";
  }

  const tests = { order: orderTest, cleanup: cleanupTest, "no new starts": noNewStartsTest };
  for (const mutant of ["none", "push", "no-return", "no-guard"]) {
    const row = [];
    for (const [name, check] of Object.entries(tests)) {
      row.push(`${name} ${(await check(mutant)) ? "pass" : "FAIL"}`);
    }
    console.log(`${mutant.padEnd(9)} | ${row.join(" | ")}`);
  }
}

main();
Text
none      | order pass | cleanup pass | no new starts pass
push      | order FAIL | cleanup pass | no new starts pass
no-return | order pass | cleanup FAIL | no new starts pass
no-guard  | order pass | cleanup pass | no new starts FAIL

With limit 1 and a failure on item 0, the correct pool checks failed before pulling again and stops, so started is just 0. The no-guard variant ignores the flag and starts items 1 and 2, which is exactly what the test records. The other two mutants pass this test, which is fine: each column only needs to fail for the bug it was written for. Limit 1 is what makes it timing-free, because there is never a second worker that could have started an item before the failure happened. After this change every mutant is killed by exactly one test, so each test has demonstrated that it is needed.

Change it and test it

Plant a fourth bug of your own in the lab, such as writing results[index + 1]. Predict which existing test catches it before running. If you have the download, make the same kind of change to map-limit.js and find the test in pool.test.js that catches it, then restore the file.

Was this article helpful?

Your response is saved on this device.