Skip to content
FrontDepth, Home

Back to the topic

Practice: Async tests and flaky tests

Answer first, then compare. Rate yourself honestly — it drives your weak-areas list.

4 predict-output · 4 open

Questions up to level

Shows questions up to the selected level.

No practice questions for this level yet.

  1. Predict the outputJunior

    A plain-JS simulation of a test runner, not Vitest: runTest awaits whatever the test function returns and prints PASS unless that throws or rejects. fetchUser resolves after 10 ms with a user named Bob, so every assertion here should fail. The unhandledRejection listener stands in for the runner's report of rejections that nobody handled. What does it log?

    JavaScript
    process.on("unhandledRejection", (error) => {
      console.log("unhandled error: " + error.message);
    });
    
    function fetchUser(id) {
      return new Promise((resolve) => setTimeout(() => resolve({ id, name: "Bob" }), 10));
    }
    
    function expectName(user, expected) {
      if (user.name !== expected) throw new Error("expected " + expected + ", got " + user.name);
    }
    
    async function runTest(name, fn) {
      try {
        await fn();
        console.log("PASS " + name);
      } catch (error) {
        console.log("FAIL " + name + ": " + error.message);
      }
    }
    
    await runTest("then without return", () => {
      fetchUser(1).then((user) => expectName(user, "Ana"));
    });
    await runTest("returned promise", () => {
      return fetchUser(1).then((user) => expectName(user, "Ana"));
    });
    await runTest("async/await", async () => {
      const user = await fetchUser(1);
      expectName(user, "Ana");
    });
    console.log("run finished");
  2. Open questionJunior

    Why can an async test pass while the code it tests is broken, and how do you prevent it?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  3. Predict the outputMiddle

    A plain-JS simulation of Testing Library's waitFor on a virtual clock, not the library: it runs the callback at once, then every 50 ms until the callback stops throwing or 1000 ms pass (the real one also re-checks when the DOM changes). In createPage, every click on Save sends a request that finishes 120 ms later, and the status reads "Saved" once any request has finished. What does it log?

    JavaScript
    function createPage() {
      let now = 0;
      const finishTimes = [];
      return {
        get now() {
          return now;
        },
        tick(ms) {
          now += ms;
        },
        clickSave() {
          finishTimes.push(now + 120);
        },
        status() {
          return finishTimes.some((time) => now >= time) ? "Saved" : "Saving";
        },
        get requests() {
          return finishTimes.length;
        },
      };
    }
    
    function waitFor(page, callback) {
      let checks = 0;
      const start = page.now;
      for (;;) {
        checks += 1;
        try {
          callback();
          return checks;
        } catch (error) {
          if (page.now - start >= 1000) throw error;
          page.tick(50);
        }
      }
    }
    
    function expectStatus(page, expected) {
      if (page.status() !== expected) throw new Error("status is " + page.status());
    }
    
    const a = createPage();
    const checksA = waitFor(a, () => {
      a.clickSave();
      expectStatus(a, "Saved");
    });
    console.log("A: checks " + checksA + ", requests " + a.requests);
    
    const b = createPage();
    b.clickSave();
    const checksB = waitFor(b, () => expectStatus(b, "Saved"));
    console.log("B: checks " + checksB + ", requests " + b.requests);
    
    const c = createPage();
    c.clickSave();
    const checksC = waitFor(c, () => c.status() === "Saved");
    console.log("C: checks " + checksC + ", status " + c.status());
  4. Predict the outputMiddle

    A plain-JS simulation of fake timers, not Vitest: createClock keeps its own timer queue. advanceBy works like vi.advanceTimersByTime: it runs due timers one after another, synchronously. advanceByAsync works like vi.advanceTimersByTimeAsync: after each timer it lets pending promise callbacks run before it looks for the next one. startPolling loads a status every second until it is "done". After advancing, each run lets pending callbacks run once more, then logs. What does it log?

    JavaScript
    function createClock() {
      let now = 0;
      const timers = [];
    
      function nextDue(end) {
        timers.sort((x, y) => x.at - y.at);
        return timers.length > 0 && timers[0].at <= end ? timers.shift() : null;
      }
    
      return {
        setTimeout(callback, ms) {
          timers.push({ at: now + ms, callback });
        },
        advanceBy(ms) {
          const end = now + ms;
          for (let timer = nextDue(end); timer; timer = nextDue(end)) {
            now = timer.at;
            timer.callback();
          }
          now = end;
        },
        async advanceByAsync(ms) {
          const end = now + ms;
          for (let timer = nextDue(end); timer; timer = nextDue(end)) {
            now = timer.at;
            timer.callback();
            // let promise callbacks run before looking for the next timer
            await new Promise((resolve) => setImmediate(resolve));
          }
          now = end;
        },
        timerCount() {
          return timers.length;
        },
      };
    }
    
    function startPolling(clock, load, show) {
      async function poll() {
        const status = await load();
        show(status);
        if (status !== "done") clock.setTimeout(poll, 1000);
      }
      clock.setTimeout(poll, 1000);
    }
    
    async function run(label, advance) {
      const clock = createClock();
      const replies = ["queued", "running", "done"];
      const shown = [];
      startPolling(clock, async () => replies.shift(), (status) => shown.push(status));
      await advance(clock);
      await new Promise((resolve) => setImmediate(resolve));
      console.log(label + ": " + shown.join(",") + " | timers left " + clock.timerCount());
    }
    
    await run("sync", (clock) => clock.advanceBy(3000));
    await run("async", (clock) => clock.advanceByAsync(3000));
  5. Open questionMiddle

    What does the "not wrapped in act(...)" warning mean in a React test, and how do you fix it properly?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  6. Open questionMiddle

    What can go wrong when you use fake timers in a React component test with Vitest, and how do you avoid it?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  7. Predict the outputSenior

    A plain-JS simulation of running one test file's tests in different orders, not Vitest: cart is module state shared by the tests of the file, and runFile starts every run with a fresh module, as Vitest does for each test file. Each test returns whether it passed. The last run adds a beforeEach that clears the cart. What does it log?

    JavaScript
    let cart = new Map();
    
    function addItem(id) {
      cart.set(id, (cart.get(id) ?? 0) + 1);
    }
    
    function itemCount() {
      let count = 0;
      for (const quantity of cart.values()) count += quantity;
      return count;
    }
    
    const tests = {
      "starts empty": () => itemCount() === 0,
      "adds an item": () => {
        addItem("mug");
        return itemCount() === 1;
      },
      "adds the same item twice": () => {
        addItem("plate");
        addItem("plate");
        return cart.get("plate") === 2;
      },
    };
    
    function runFile(order, beforeEach) {
      cart = new Map(); // each test file gets a fresh module
      const results = order.map((name) => {
        if (beforeEach) beforeEach();
        return tests[name]() ? "pass" : "FAIL";
      });
      console.log(results.join(" "));
    }
    
    const written = ["starts empty", "adds an item", "adds the same item twice"];
    runFile(written);
    runFile(["adds an item", "starts empty", "adds the same item twice"]);
    runFile(["adds the same item twice", "adds an item", "starts empty"]);
    runFile(["adds the same item twice", "adds an item", "starts empty"], () => cart.clear());
  8. Open questionSenior

    A test fails in about 1 of 20 CI runs and never on your machine. How do you approach it?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.