Skip to content

Controlled Async Tests

The Course
•
20 min study

An async test should control the event it is testing. Sleeping for 20 milliseconds and hoping another operation completed can pass on one machine and fail under load. A deferred promise gives the test an explicit release point.

A test can first observe what has started, release one job, await an explicit notification that another started, and only then inspect the next state. That checks causality. Merely awaiting Promise.resolve once is not a general “flush all async work” operation; it only schedules another promise reaction.

Our pool tests use a separate third-started gate to prove a slot was refilled before releasing the first job. They also verify the outer promise has not settled while an active peer remains blocked after a failure. Test both the order and the lifecycle boundary, not just the final array.

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() {
  function deferred() {
    let resolve;
    const promise = new Promise(done => {
      resolve = done;
    });

    return { promise, resolve };
  }

  const gate = deferred();
  let finished = false;
  const work = gate.promise.then(() => {
    finished = true;
  });

  console.log(finished);
  gate.resolve();
  await work;
  console.log(finished);
}

main();
Check your prediction
Text
false
true

Wait for a meaningful event rather than elapsed time

A controlled promise lets a test hold one operation at a chosen point. The test should observe the pending state, release the gate, then await the actual operation. Sleeping for an arbitrary interval hides whether the state changed for the reason you intended.

For a pool refill test, use a notification from the next mapper invocation. A microtask turn is not evidence that an arbitrary chain completed. Test causal events through the API rather than trying to flush every possible asynchronous operation.

Wait for a meaningful event rather than elapsed time: trace JavaScript
async function main() {
  let release;
  const gate = new Promise(resolve => {
    release = resolve;
  });
  const events = [];
  const work = gate.then(() => {
    events.push("done");
  });

  console.log(events.length);
  release();
  await work;
  console.log(events.join(","));
}

main();
Check your prediction
Text
0
done

The first observation proves work is still held. The awaited promise in the second observation is the one that performs the effect, not an unrelated promise resolved nearby.

Wait for a meaningful event rather than elapsed time: contrast JavaScript
async function main() {
  let notify;
  const started = new Promise(resolve => {
    notify = resolve;
  });

  async function job() {
    notify();
    return 25;
  }

  const work = job();

  await started;
  console.log("start observed");
  console.log(await work);
}

main();
Check your prediction
Text
start observed
25

A separate notification can prove a phase began. In a real test it can notify that the third pool job started while another is still held, distinguishing refill from batch behavior.

Try the rule on new inputs

Create separate started and released gates. Prove an outer promise stays pending while an active callback remains held after a peer fails. Add a timeout only as a safety limit for a broken test.

A worked limit-2 test: refill and still pending

Here is the kind of test the pool's own suite uses, on a small limit-2 pool. controlledMapper gives the test two tools. Each call waits on its own deferred gate, which the test resolves or rejects. And waitForStarts(n) is a promise that resolves only once the mapper has been called n times: a notification, not a guess. Predict the five lines.

Prove a refill, then prove the pool is still waiting JavaScript
async function main() {
  // A small limit-2 pool: refills free slots; on failure it aborts the
  // others, waits for every started job, then rejects.
  async function pool(values, mapper, limit) {
    const controller = new AbortController();
    let next = 0;
    let failed = false;
    let failure;
    const results = [];
    async function worker() {
      while (!failed && next < values.length) {
        const index = next++;
        try {
          results[index] = await mapper(values[index], index, controller.signal);
        } catch (error) {
          if (!failed) {
            failed = true;
            failure = error;
            controller.abort(error);
          }
        }
      }
    }
    await Promise.all(Array.from({ length: limit }, () => worker()));
    if (failed) throw failure;
    return results;
  }

  // ---- test helpers ----
  function deferred() {
    let resolve, reject;
    const promise = new Promise((yes, no) => {
      resolve = yes;
      reject = no;
    });
    return { promise, resolve, reject };
  }

  function controlledMapper() {
    const gates = [];
    const started = [];
    const waiting = [];
    function waitForStarts(count) {
      if (started.length >= count) return Promise.resolve();
      const gate = deferred();
      waiting.push({ count, gate });
      return gate.promise;
    }
    function mapper(value, index, signal) {
      started.push(index);
      gates[index] = deferred();
      for (const w of waiting) if (started.length >= w.count) w.gate.resolve();
      return gates[index].promise;
    }
    return { mapper, gates, started, waitForStarts };
  }

  // Test 1: a finished slot is refilled before the slow job ends.
  const t1 = controlledMapper();
  const run1 = pool(["a", "b", "c"], t1.mapper, 2);
  await t1.waitForStarts(2);
  console.log(`started: ${t1.started.join(",")}`);
  t1.gates[1].resolve("B");
  await t1.waitForStarts(3); // resolves only if job 2 actually starts
  console.log(`refilled while 0 is held: ${t1.started.join(",")}`);
  t1.gates[0].resolve("A");
  t1.gates[2].resolve("C");
  console.log(`result: ${(await run1).join(",")}`);

  // Test 2: after a failure, the pool waits for the held peer.
  const t2 = controlledMapper();
  const run2 = pool(["x", "y", "z"], t2.mapper, 2);
  let settled = false;
  run2.then(
    () => (settled = true),
    () => (settled = true)
  );
  await t2.waitForStarts(2);
  t2.gates[1].reject(new Error("y failed"));
  await new Promise(resolve => setTimeout(resolve, 0));
  console.log(`after failure: settled ${settled}, started ${t2.started.join(",")}`);
  t2.gates[0].resolve("X");
  try {
    await run2;
  } catch (error) {
    console.log(`after release: rejected with "${error.message}"`);
  }
}

main();
Check your prediction
Text
started: 0,1
refilled while 0 is held: 0,1,2
result: A,B,C
after failure: settled false, started 0,1
after release: rejected with "y failed"

Test 1 never sleeps. waitForStarts(2) resolves when the mapper has been called twice, so started: 0,1 is checked at the moment it becomes true. Releasing job 1 and then awaiting waitForStarts(3) is the refill proof: that promise can only resolve if the pool calls the mapper a third time while job 0 is still held. In a batch implementation it would never resolve, and the test would time out at that line instead of passing by luck. Test 2 checks something that has not happened. After job 1 fails, one timer turn (setTimeout(..., 0)) lets every pending promise reaction run, and settled is still false because job 0 is held, while job 2 never started because the pool stopped taking new work. Only after the test releases job 0 does the pool reject, with job 1's error.

Trace the contract before building

A deferred promise gives the test authority over a completion point. Retain its resolver, start the operation under test, inspect what has started, then resolve jobs in a chosen order. This makes the schedule an explicit input rather than a guess about elapsed time.

Keep assertions at meaningful boundaries. Check how many jobs start before releasing capacity, then check result placement after out-of-order completion. A final array alone can miss temporary over-concurrency or unnecessary source pulls. Resolve or reject every controlled operation during cleanup so a failing test does not leave ambiguous background work.

Your turn

Exercise

Write the test that catches an eager queue

Two queues are supplied. Both claim "tasks run one at a time, in order"; only createSerialQueue keeps that promise. Write check(createQueue), a test that returns PASS for the serial queue and FAIL for the eager one, without any timer other than the supplied tick. It should report two facts: whether the second task waited (not started, and its promise not settled, while the first is held), and whether, after release, the tasks started and finished in order. Print:

Text
serial: waited: true | ordered after release: true | PASS
eager:  waited: false | ordered after release: true | FAIL
Your workspace JavaScript
async function main() {
  // Two queues to test. Each promises: tasks run one at a time, in order.
  function createSerialQueue() {
    let tail = Promise.resolve();
    return task => {
      const run = tail.then(() => task());
      tail = run.catch(() => {});
      return run;
    };
  }
  function createEagerQueue() {
    return task => Promise.resolve().then(() => task()); // starts at once
  }

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

  async function check(createQueue) {
    const enqueue = createQueue();
    // 1. Enqueue a first task that records start 1 and waits on a deferred,
    //    and a second task that records start 2 and returns "second".
    // 2. Before releasing: has 2 started? has the second promise settled?
    // 3. Release, await both, then check order and results.
    return "TODO";
  }

  console.log(`serial: ${await check(createSerialQueue)}`);
  console.log(`eager:  ${await check(createEagerQueue)}`);
}

main();
Hint 1: the idea

Both queues finish with first,second, so a test that only awaits the results would pass both. The difference is visible only while the first task is held: you need a deferred to hold it, a list of starts, and a settled flag on the second task's promise.

Hint 2: a first step

Create first = deferred() and enqueue a task that pushes 1 to started and returns first.promise. Enqueue a second that pushes 2 and returns "second", and attach .then(() => (twoSettled = true)) to its promise. After await tick(), print started for both queues before writing any assertions: you should see 1 for serial and 1,2 for eager.

Show one solution
JavaScript
async function main() {
  // Two queues to test. Each promises: tasks run one at a time, in order.
  function createSerialQueue() {
    let tail = Promise.resolve();
    return task => {
      const run = tail.then(() => task());
      tail = run.catch(() => {});
      return run;
    };
  }
  function createEagerQueue() {
    return task => Promise.resolve().then(() => task()); // starts at once
  }

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

  async function check(createQueue) {
    const enqueue = createQueue();
    const first = deferred();
    const started = [];

    const one = enqueue(() => {
      started.push(1);
      return first.promise;
    });
    const two = enqueue(() => {
      started.push(2);
      return "second";
    });

    let twoSettled = false;
    two.then(() => (twoSettled = true));

    await tick();
    const waited = started.join(",") === "1" && !twoSettled;

    first.resolve("first");
    const results = await Promise.all([one, two]);
    const ordered = started.join(",") === "1,2" && results.join(",") === "first,second";

    return `waited: ${waited} | ordered after release: ${ordered} | ${waited && ordered ? "PASS" : "FAIL"}`;
  }

  console.log(`serial: ${await check(createSerialQueue)}`);
  console.log(`eager:  ${await check(createEagerQueue)}`);
}

main();
Text
serial: waited: true | ordered after release: true | PASS
eager:  waited: false | ordered after release: true | FAIL

The ordered check alone gives true for both queues: if the test had only awaited the results, the eager queue would pass. What separates them is the waited check, taken while the first task is held on a deferred that only the test can release. await tick() gives the eager queue every chance to start task 2 (it does), and for the serial queue it shows that task 2 has neither started nor settled. Because the release happens only after that observation, the result does not depend on how fast the machine is. This is the same pattern as the pool's refill test: hold, observe, release, observe again.

Change it and test it

Release two gates in reverse order and assert the observed completion order. Then explain which signal a test should await to know that a third pool job started. A timeout may be a final safety net for a broken test, but should not create its intended ordering.

Was this article helpful?

Your response is saved on this device.