Testing Asynchronous Code and Timers
Build a working model of automated testing from assertions to unit, component, API, integration, contract and end-to-end tests, then apply it to a single progressive task-board capstone where each milestone adds a real defect, a failing test, a corrected implementation and an expected result.
What you will be able to do
#- Await asynchronous assertions instead of asserting before they settle.
- Replace real timers with a controllable clock.
- Test rejection paths as carefully as resolution paths.
Overview
#The classic async mistake
An asynchronous test that does not wait for the promise to settle asserts on a value that is still pending. The assertion runs, sees the initial state, and passes or fails for the wrong reason. If the assertion is inside a callback that never runs, the test may pass without testing anything.
// wrong: assertion runs before the promise resolves
function loadUser() {
return Promise.resolve({ id: 1 });
}
let user;
loadUser().then((u) => { user = u; });
console.log(user === undefined); // true, the then has not run yet
Await the work
Mark the test async and await the promise before asserting. The assertion then runs after the value is available. If the code under test uses callbacks instead of promises, wrap the callback in a promise and await that.
Fake timers
A function that debounces for 300 milliseconds should not make the suite slow or flaky. A fake timer replaces the real clock so the test can advance time instantly and deterministically. The pattern is: install fake timers, call the code, advance time by the debounce interval, then assert that the effect fired exactly once.
let calls = 0;
const debounced = debounce(() => { calls += 1; }, 300);
debounced();
debounced();
debounced();
// advance the fake clock by 300ms here
console.log(calls); // 1
Test rejection, not just resolution
Every promise path has two outcomes. A test suite that only checks the resolved value misses the error handling entirely. Assert that a rejected promise rejects with the expected error, and that a function converts a rejection into the correct fallback. Use await expect(promise).rejects style checks or a try/catch that fails if no error was thrown.
Do not leave timers running
A real timer left running after a test can fire during a later test, causing an unrelated failure. Clear timers in cleanup, or use fake timers so nothing is scheduled on the real clock.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does this print?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptlet value = 'initial'; Promise.resolve().then(() => { value = 'resolved'; }); console.log(value);Exercise 2Explain
Explain why a test that asserts inside a `.then` callback can pass without testing anything.
Reveal the reference answer
reference.javascriptIf the test function returns before the promise settles, the runner may consider the test complete and report success while the callback is still queued. The assertion may run later or never, and a thrown error inside the callback can be swallowed. Awaiting the promise keeps the test open until the assertion has actually run, so a failure is reported to the runner.The answer should identify the timing gap between test completion and callback execution and the swallowed-error risk.
Exercise 3Implement
Implement `withFakeTimers(run)` that lets `run` schedule timers but executes scheduled callbacks only when `run` calls `advance(ms)`. Keep it minimal: `run` receives `{ setTimeout, advance }`. `withFakeTimers(({ setTimeout, advance }) => { let hit = false; setTimeout(() => { hit = true; }, 100); advance(100); console.log(hit); })` should print `true`.
starter.javascriptfunction withFakeTimers(run) { // your code here }Reveal the reference answer
reference.javascriptfunction withFakeTimers(run) { const queue = []; let now = 0; const setTimeoutFake = (fn, delay) => { queue.push({ fn, at: now + delay }); }; const advance = (ms) => { now += ms; queue.sort((a, b) => a.at - b.at); while (queue.length && queue[0].at <= now) { queue.shift().fn(); } }; run({ setTimeout: setTimeoutFake, advance }); }Authored expected output: true
Timers are stored with their due time instead of handed to the real clock. advance moves the virtual clock forward and runs every callback whose due time has passed, in order. This is the core idea of a fake timer.
Exercise 4Debug
This async test reads `result` before the promise resolves, so it always throws for the wrong reason instead of checking the resolved value. Fix the timing bug.
starter.javascriptfunction fetchCount() { return Promise.resolve(42); } let result; fetchCount().then((n) => { result = n; }); if (result === 42) { console.log('pass'); } else { throw new Error('expected 42 but got ' + result); }Reveal the reference answer
reference.javascriptfunction fetchCount() { return Promise.resolve(42); } async function test() { const result = await fetchCount(); if (result === 42) { console.log('pass'); } else { throw new Error('expected 42 but got ' + result); } } test();Authored expected output: pass
The original reads result synchronously, before the then callback runs, so result is undefined and the check always throws. Awaiting the promise assigns result after it resolves, so the assertion sees the real value.
Exercise 5Test
Write a test that proves a `retry` helper resolves after a transient rejection and rejects after exhausting attempts.
starter.javascriptasync function retry(fn, attempts) { let lastError; for (let i = 0; i < attempts; i++) { try { return await fn(); } catch (error) { lastError = error; } } throw lastError; }Reveal the reference answer
reference.javascriptfunction assertEqual(actual, expected, label) { if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual); } async function test() { let calls = 0; const flaky = () => { calls += 1; return calls < 3 ? Promise.reject(new Error('transient')) : Promise.resolve('ok'); }; assertEqual(await retry(flaky, 3), 'ok', 'resolves after retry'); let alwaysFail = 0; const failing = () => { alwaysFail += 1; return Promise.reject(new Error('permanent')); }; let threw = false; try { await retry(failing, 2); } catch (error) { threw = true; } assertEqual(threw, true, 'rejects after exhausting attempts'); assertEqual(alwaysFail, 2, 'attempt count'); console.log('retry verified'); } test();Authored expected output: retry verified
The first assertion covers the success-after-retry path. The second and third cover the exhaustion path and prove the helper did not retry more than the allowed attempts. Both outcomes of the promise are tested.
Exercise 6Interview
In an interview, explain how you would test a debounced search input without slowing the suite.
Reveal the reference answer
reference.javascriptI inject the debounce delay and the timer functions so the test controls time. I install a fake clock, simulate several rapid input events, advance the clock by the debounce interval, and assert the search fired exactly once with the final query. I also advance less than the interval and assert it did not fire, which covers the cancellation path. No real waiting is involved, so the test is fast and deterministic.The answer should combine dependency injection, fake timers, and an assertion on both the firing and the non-firing cases.
Common misconceptions
#- A test with a `.then` callback automatically waits for the callback.
- Fake timers make tests less realistic and therefore less valuable.
- Testing the resolved value is enough for an async function.
Follow-up practice
#- testing-network-and-api
- testing-flaky-and-deterministic
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.