Skip to content

Async Integration Tests

The Course
•
16 min study

Choose the schedule, then check the commits

A unit test can prove a decoder rejects malformed data. An integration test checks that the controller actually calls that decoder before rendering results. Likewise, a token helper may be correct while a forgotten guard in catch still displays an obsolete error.

Use deferred promises to choose fulfillment and rejection order. Start old, start new, finish new, then finish old. Assert the final state and the renderer's observed states. Repeat with an old rejection. A sleep-based test that merely waits "long enough" does not prove these ordering cases reliably.

After cancel, fulfill the old promise anyway and assert no late result appears. This simulates a transport ignoring cancellation. After dispose, fulfill or reject pending work and assert no new render. Also test a rejected current request, empty success, and invalid response shape so the happy path does not dominate your evidence.

The downloaded project includes Node's built-in test runner: node:test defines a test and node:assert/strict checks outcomes, including deepEqual for structured values. You do not need that runner inside the console editor; the checks below use ordinary throws. The framework organizes tests, but the important work is choosing the cases.

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
async function main() {
  function deferred() {
    let reject;
    const promise = new Promise((resolve, fail) => {
      reject = fail;
    });

    return { promise, reject };
  }

  const pending = deferred();
  const messages = [];

  async function attempt() {
    try {
      await pending.promise;
      messages.push("ready");
    } catch (error) {
      messages.push(error.message);
    }
  }

  const run = attempt();

  pending.reject(new Error("chosen failure"));
  await run;

  if (messages[0] !== "chosen failure") {
    throw new Error("wrong outcome");
  }

  console.log("Controlled rejection passed");
}

main();
Check your prediction
Text
Controlled rejection passed

The rejection handler is attached before we reject. Nothing waits an arbitrary number of milliseconds.

Control the event that proves progress

A schedule test needs evidence that the relevant step happened, not a guessed delay. Retain a resolver or rejection function and release it after asserting the pending state. Await the actual operation before inspecting its final effects.

When testing a controller, use injected dependencies to observe loading, completion and cleanup. Test the integration between parts through their public effects. A reducer test alone cannot prove that the controller attached the right request id or respected disposal.

Control the event that proves progress: trace JavaScript
async function main() {
  let release;
  const pending = new Promise(resolve => {
    release = resolve;
  });
  const events = [];

  async function run() {
    events.push("loading");
    await pending;
    events.push("ready");
  }

  const work = run();

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

main();
Check your prediction
Text
loading
loading,ready

The first observation happens while the operation is genuinely held. The second happens after its returned promise settles, so the test has a causal completion signal.

Control the event that proves progress: contrast JavaScript
async function main() {
  let starts = 0;

  async function request() {
    starts++;
    throw new Error("offline");
  }

  let message = "";

  try {
    await request();
  } catch (error) {
    message = error.message;
  }

  if (starts !== 1 || message !== "offline") {
    throw new Error("Wrong integration");
  }

  console.log("call count and failure checked");
}

main();
Check your prediction
Text
call count and failure checked

The observed message and dependency call count protect different behavior. A controller that retries without permission could display the right error but still violate the one-call contract.

Try the rule on new inputs

Create controlled success, controlled failure, stale completion and completion-after-disposal cases. Remove one controller guard and confirm a particular schedule fails. Keep timers only as a final hung-test safety limit.

Drive the real controller

The program below is the capstone's actual createController (with its model), driven by a fake search that hands back a deferred promise per query. Each schedule records what render saw: the status, or the first title once results are ready. Four schedules cover the controller's promises: a newer search beats an older one, an older failure after a newer success is ignored, cancel hides a late result, and dispose stops all rendering.

Schedules against createController JavaScript
async function main() { // Deterministic schedule tests that drive the project's real controller. function deferred() { let resolve; let reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; } // Each search call gets its own deferred response, kept by query. function harness() { const pending = {}; const renders = []; const app = createController({ search(query) { pending[query] = deferred(); return pending[query].promise; }, render(state) { renders.push(state.status === "ready" ? state.results[0].title : state.status); } }); return { app, pending, renders }; } const flush = () => new Promise(resolve => setTimeout(resolve, 0)); async function newerWins() { const { app, pending, renders } = harness(); const old = app.load("old"); const recent = app.load("new"); pending.new.resolve([{ id: "n", title: "New" }]); await recent; pending.old.resolve([{ id: "o", title: "Old" }]); await old; return renders.join(" > "); } async function staleFailureIgnored() { const { app, pending, renders } = harness(); const old = app.load("old"); const recent = app.load("new"); pending.new.resolve([{ id: "n", title: "New" }]); await recent; pending.old.reject(new Error("Old search failed")); await old; return renders.join(" > "); } async function cancelThenLate() { const { app, pending, renders } = harness(); const load = app.load("old"); app.cancel(); pending.old.resolve([{ id: "o", title: "Old" }]); // the transport ignored abort await load; return renders.join(" > "); } async function disposeThenLate() { const { app, pending, renders } = harness(); const load = app.load("old"); app.dispose(); pending.old.resolve([{ id: "o", title: "Old" }]); await load; await flush(); return renders.join(" > "); } for (const schedule of [newerWins, staleFailureIgnored, cancelThenLate, disposeThenLate]) { console.log(`${schedule.name}: ${await schedule()}`); } function decodeBooks(value) { if (!Array.isArray(value)) { throw new Error("Expected a list of books"); } const ids = new Set(); return value.map(item => { if ( item === null || typeof item !== "object" || Array.isArray(item) || typeof item.id !== "string" || item.id.trim() === "" || typeof item.title !== "string" || item.title.trim() === "" ) { throw new Error("Each book needs an id and title"); } const id = item.id.trim(); if (ids.has(id)) { throw new Error("Duplicate book id"); } ids.add(id); return { id, title: item.title.trim() }; }); } function toggleSaved(saved, book) { if (saved.some(item => item.id === book.id)) { return saved.filter(item => item.id !== book.id); } return [...saved, { ...book }]; } function initialState(saved = []) { return { status: "idle", results: [], saved, error: "" }; } function reduce(state, action) { switch (action.type) { case "loading": return { ...state, status: "loading", results: [], error: "" }; case "loaded": return { ...state, status: "ready", results: action.books, error: "" }; case "failed": return { ...state, status: "error", results: [], error: action.message }; case "cancelled": return { ...state, status: "idle", results: [], error: "" }; case "toggle": return { ...state, saved: toggleSaved(state.saved, action.book) }; default: throw new Error("Unknown action"); } } // search(query, { signal }) returns a promise for untrusted book data. function createController({ search, render, saved = [] }) { let state = initialState(saved); let generation = 0; let active = null; let disposed = false; const send = action => { state = reduce(state, action); render(state); }; return { getState() { return state; }, async load(text) { if (disposed) { return; } const query = text.trim(); const mine = ++generation; active?.abort(); active = null; if (!query) { send({ type: "failed", message: "Enter a search topic." }); return; } active = new AbortController(); const request = active; send({ type: "loading" }); try { const books = decodeBooks( await search(query, { signal: request.signal }) ); if (disposed || mine !== generation) { return; } send({ type: "loaded", books }); } catch (error) { if (disposed || mine !== generation) { return; } send({ type: "failed", message: error instanceof Error ? error.message : "Search failed" }); } finally { if (mine === generation) { active = null; } } }, cancel() { if (disposed) { return; } generation += 1; active?.abort(); active = null; send({ type: "cancelled" }); }, toggle(book) { if (!disposed) { send({ type: "toggle", book }); } }, dispose() { disposed = true; generation += 1; active?.abort(); active = null; } }; } } main();
Check your prediction
Text
newerWins: loading > loading > New
staleFailureIgnored: loading > loading > New
cancelThenLate: loading > idle
disposeThenLate: loading

Every second loading is the newer search starting. The old search's late success or failure never reaches render, because both completion paths check mine !== generation. cancel renders idle and bumps the generation, so the late "Old" is dropped. dispose renders nothing at all. Try it: scroll to createController in the editor, change the guard in its catch from if (disposed || mine !== generation) to if (disposed), and run again. Only staleFailureIgnored changes, now ending > error. That is the case that protects that line.

Build it yourself

Exercise

Prove a stale-result guard

createLatest(load, render) is a cut-down controller: each run(query) renders ready <value> or error <message>, but only for the most recent run. createLatestUnguarded is the same with a defect in one path. Write checkLatest(create) with three deferred schedules, each comparing the renders with an expected string: newer result wins ("ready new"), stale failure ignored ("ready new"), and current failure shown ("error offline"). The defect should be named by exactly one check:

Text
createLatest: passed
createLatestUnguarded: FAILED stale failure ignored
Your working space JavaScript
async function main() {
  function createLatest(load, render) {
    let generation = 0;
    return async function run(query) {
      const mine = ++generation;
      try {
        const value = await load(query);
        if (mine === generation) render(`ready ${value}`);
      } catch (error) {
        if (mine === generation) render(`error ${error.message}`);
      }
    };
  }

  // A deliberate defect: the failure path forgot the generation check.
  function createLatestUnguarded(load, render) {
    let generation = 0;
    return async function run(query) {
      const mine = ++generation;
      try {
        const value = await load(query);
        if (mine === generation) render(`ready ${value}`);
      } catch (error) {
        render(`error ${error.message}`);
      }
    };
  }

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

  async function checkLatest(create) {
    const failures = [];
    // For each schedule: create a fresh run with deferred loads,
    // drive the schedule, compare the renders, record the label on a mismatch.
    return failures;
  }

  for (const create of [createLatest, createLatestUnguarded]) {
    const failures = await checkLatest(create);
    console.log(`${create.name}: ${failures.length ? "FAILED " + failures.join(", ") : "passed"}`);
  }
}

main();
Hint 1: the idea

A schedule test has three parts: start the runs, settle their deferred loads in a chosen order, then wait for the runs and compare what render recorded. The defect only shows if the older load settles after the newer one, and fails.

Hint 2: a first step

Write a helper schedule(label, steps, expected) that creates a fresh run whose load stores a deferred() under the query, and pushes rendered text into an array. Use it for "current failure shown" first: one run, reject its load, await it. Both versions should still print passed, because that schedule cannot see the bug.

Show one solution
JavaScript
async function main() {
  function createLatest(load, render) {
    let generation = 0;
    return async function run(query) {
      const mine = ++generation;
      try {
        const value = await load(query);
        if (mine === generation) render(`ready ${value}`);
      } catch (error) {
        if (mine === generation) render(`error ${error.message}`);
      }
    };
  }

  // A deliberate defect: the failure path forgot the generation check.
  function createLatestUnguarded(load, render) {
    let generation = 0;
    return async function run(query) {
      const mine = ++generation;
      try {
        const value = await load(query);
        if (mine === generation) render(`ready ${value}`);
      } catch (error) {
        render(`error ${error.message}`);
      }
    };
  }

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

  async function checkLatest(create) {
    const failures = [];

    async function schedule(label, steps, expected) {
      const pending = {};
      const renders = [];
      const run = create(query => {
        pending[query] = deferred();
        return pending[query].promise;
      }, text => renders.push(text));
      await steps(run, pending);
      if (renders.join(" | ") !== expected) failures.push(label);
    }

    await schedule("newer result wins", async (run, pending) => {
      const old = run("old");
      const recent = run("new");
      pending.new.resolve("new");
      pending.old.resolve("old");
      await Promise.all([old, recent]);
    }, "ready new");

    await schedule("stale failure ignored", async (run, pending) => {
      const old = run("old");
      const recent = run("new");
      pending.new.resolve("new");
      await recent;
      pending.old.reject(new Error("old failed"));
      await old;
    }, "ready new");

    await schedule("current failure shown", async (run, pending) => {
      const only = run("only");
      pending.only.reject(new Error("offline"));
      await only;
    }, "error offline");

    return failures;
  }

  for (const create of [createLatest, createLatestUnguarded]) {
    const failures = await checkLatest(create);
    console.log(`${create.name}: ${failures.length ? "FAILED " + failures.join(", ") : "passed"}`);
  }
}

main();
Text
createLatest: passed
createLatestUnguarded: FAILED stale failure ignored

The unguarded version passes "newer result wins" and "current failure shown", because its success path and the newest run's failure are both correct. Only a schedule in which an older run fails after a newer one has rendered reaches the missing check, and its extra error old failed render makes the comparison fail. Awaiting recent before rejecting old fixes that order deterministically; a sleep of a few milliseconds would only make it likely. Each schedule builds a fresh run, so one case's generation counter never leaks into the next.

Explain before moving on

Which property of an async test is controlled by a deferred promise? Why must stale rejection be tested separately from stale success?

Was this article helpful?

Your response is saved on this device.