Skip to content
FrontDepth, Home

Testing

Async tests and flaky tests

How to test async code without false passes or random failures: awaiting everything, findBy and waitFor, what the act() warning means, Vitest fake timers and their async variants, why tests flake (timing, shared state, order, network, randomness, time zones) and how to find and fix them instead of retrying.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

This topic starts at Junior level.

JuniorPitfalls

Tests that pass without checking anything

A test runner can only judge what the test function gives back. If the function returns before the async work is done, the runner sees no error and marks the test as passed.

TypeScript
test("loads the user", () => {
  fetchUser(1).then((user) => {
    expect(user.name).toBe("Ana");
  });
});

The function starts the request and returns undefined straight away, so the test passes. The assertion runs later, if at all. When it fails, the error is a rejected promise that nobody handles: Vitest reports unhandled rejections as errors of the whole run, not as a failure of this test, and if the test file finishes before the request does, the assertion may never run.

Make the test wait for the work it checks:

TypeScript
test("loads the user", async () => {
  const user = await fetchUser(1);
  expect(user.name).toBe("Ana");
});

Returning the promise (return fetchUser(1).then(...)) works too; async/await is easier to read.

The same bug in UI tests

  • user.click(button) without await: the next line runs before the click has finished. An absence check such as expect(screen.queryByText("Could not delete")).not.toBeInTheDocument() then passes, because nothing has happened yet.
  • screen.findByText("Saved") as a statement without await: nothing waits for it and nothing checks the result.
  • waitFor(() => expect(...)) without await: a timeout inside it can never fail the test.
  • expect(promise).resolves.toBe(...) without await: Vitest detects this one and fails the test at the end, but the others go unnoticed.

Guards

  • expect.hasAssertions() fails a test in which no assertion ran; expect.assertions(2) demands an exact count. With either one, the first example above fails: no assertion has run when the test ends. The expect.requireAssertions config option applies the "at least one" rule to every test.
  • typescript-eslint's no-floating-promises reports promise statements that are not awaited, returned or handled.
  • eslint-plugin-testing-library has await-async-queries, await-async-events and await-async-utils for findBy, user-event and waitFor.
  • Watch every new test fail once. A test you have never seen fail may not be testing anything.
JuniorConcept

Waiting for the UI: findBy and waitFor

When the UI changes after a request, a timer or an effect, the test has to wait. The tempting way is a fixed pause:

TSX
await new Promise((resolve) => setTimeout(resolve, 500));
expect(screen.getByText("Saved")).toBeInTheDocument();

On a fast laptop that wastes time; on a busy CI machine 500 ms is sometimes not enough, and the test flakes. Martin Fowler's advice is to "never use bare sleeps" and to use a callback or polling instead. Testing Library's waiting helpers are polling done for you.

findBy

TSX
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByRole("status")).toHaveTextContent("Saved");

findBy resolves as soon as the element appears and rejects after 1000 ms by default. It takes the wait options as a third argument: findByRole("status", {}, { timeout: 3000 }).

waitFor

waitFor(callback) is the general form. It runs the callback immediately, then again every 50 ms and whenever the DOM changes, until the callback stops throwing or the timeout (1000 ms) passes. Then it rejects with the last error.

TSX
await waitFor(() => expect(onSave).toHaveBeenCalledWith({ name: "Ana" }));

Returning false is not enough: the callback has to throw to be retried. That is why expect belongs inside it. For something that should disappear, waitForElementToBeRemoved(() => screen.queryByText("Loading...")) waits until the element is gone. It throws at once if the element is not there to begin with, which catches a test that waits for the wrong thing.

Rules that keep waiting reliable

Kent C. Dodds lists these among the common mistakes with Testing Library:

  • Prefer findBy over waitFor plus getBy. Same behaviour, shorter, with a better error message.
  • Never pass an empty callback (await waitFor(() => {})). It checks nothing, and the test breaks as soon as the async logic changes. Wait for a specific assertion.
  • Put one assertion in a callback. If an assertion that will never pass shares the callback, waitFor keeps retrying until the timeout before it reports the failure. Assert the rest after the wait, where they fail at once.
  • Keep side effects out of the callback. A click inside waitFor runs again on every retry.
MiddleFramework

What the act() warning means

React's act() makes sure that the updates and effects triggered inside it have been applied before your next line runs, the way they would be by the time a user sees the screen. React Testing Library wraps render and fireEvent in act, user-event's events go through the same wrapper, and while waitFor and findBy wait, it turns the act check off so updates during the wait do not warn. Most tests never call act themselves.

The warning looks like this:

Text
An update to ProfileForm inside a test was not wrapped in act(...).

It means React saw a state update that nothing in the test was waiting for. Usually the test made its assertions and moved on while a promise started by the component was still pending, and that promise later set state. The test checked the UI before it had settled, and the update lands at a moment the test does not control.

TSX
test("saves the profile", async () => {
  const user = userEvent.setup();
  const onSave = vi.fn().mockResolvedValue(undefined);
  render(<ProfileForm onSave={onSave} />);

  await user.click(screen.getByRole("button", { name: "Save" }));
  expect(onSave).toHaveBeenCalled();
  // onSave resolves after this line, and the form sets "Saved": the warning
});

The fix is not more act, but waiting for what the user would wait for:

TSX
  expect(await screen.findByRole("status")).toHaveTextContent("Saved");

Now the update happens while Testing Library is waiting, and the test checks the final state too.

When you call act yourself

  • Fake timers: advancing them runs callbacks that may set state, outside any Testing Library call: act(() => { vi.advanceTimersByTime(5000); }).
  • Updates the test triggers directly, such as calling a store's method or a renderHook result's function.

For async work, react.dev recommends the async form, await act(async () => { ... }). In React 19, import act from react; the old import from react-dom/test-utils is deprecated.

The environment flag

React 18 introduced globalThis.IS_REACT_ACT_ENVIRONMENT; React reports updates outside act only when it is true. React Testing Library sets it in a global beforeAll, so with Vitest set globals: true or set the flag in your setup file. Otherwise the warning never appears, and the problem it points at stays hidden.

Do not silence the warning. It points at an update your test did not wait for, and that update is often what turns into a flaky test later.

MiddleFramework

Fake timers in Vitest

A notice that hides after 5 seconds, a of 300 ms or a session warning after 15 minutes: waiting for these in real time makes tests slow, and racing them makes tests flaky. replace the timer functions with a clock that only moves when the test moves it.

TSX
beforeEach(() => {
  vi.useFakeTimers();
});

afterEach(() => {
  vi.useRealTimers();
});

test("hides the notice after 5 seconds", () => {
  render(<SavedNotice />);

  act(() => {
    vi.advanceTimersByTime(4999);
  });
  expect(screen.getByRole("status")).toHaveTextContent("Saved");

  act(() => {
    vi.advanceTimersByTime(1);
  });
  expect(screen.queryByRole("status")).not.toBeInTheDocument();
});

The test takes milliseconds and checks both sides of the boundary. act is there because the timer callback sets state outside any Testing Library call.

What gets faked

vi.useFakeTimers() fakes setTimeout, setInterval, setImmediate, their clear functions, Date, and by default everything else of that kind the environment provides, such as requestAnimationFrame and performance, except process.nextTick and queueMicrotask. Promises are not timers: promise callbacks still run as , on their own schedule.

Moving the clock

  • vi.advanceTimersByTime(ms): runs every timer that falls due within ms.
  • vi.advanceTimersToNextTimer(): jumps to the next timer and runs it.
  • vi.runOnlyPendingTimers(): runs the timers already scheduled, but not new ones they create.
  • vi.runAllTimers(): runs timers until none are left. An endless interval makes it throw after 10,000 timers (the loopLimit option).
  • vi.getTimerCount(): how many timers are waiting. Useful to check that a component cleaned up.
  • vi.setSystemTime(date): changes what Date.now() and new Date() return without running any timers. It is the tool for "today" and "end of the month" cases.

Turning them off

vi.useRealTimers() restores the real functions, and timers still scheduled are discarded. Testing Library's guide suggests running the pending timers first, so work scheduled by a library you did not write is not silently lost. Restore real timers after every test; fake timers that leak into the next test are a classic cause of confusing failures.

Fake timers are not always the better choice. If the delay is short, real timers with findBy are often simpler.

MiddlePitfalls

When fake timers meet promises

Most surprises with fake timers come from code that mixes timers and promises. Take a status poller:

TypeScript
export function startPolling(load: () => Promise<string>, show: (status: string) => void) {
  async function poll() {
    const status = await load();
    show(status);
    if (status !== "done") setTimeout(poll, 1000);
  }
  setTimeout(poll, 1000);
}

With fake timers on and load returning "queued", "running" and "done", a test calls vi.advanceTimersByTime(3000) and expects three updates. It gets one. The first poll runs at 1000 ms and stops at await load(); the rest of poll is a promise callback, a microtask, and microtasks run only after the synchronous advanceTimersByTime has returned. By then it found no other timer in the range, so the clock simply moved to 3000 ms. The next timer is scheduled later, from the new time. This is the working as usual: timers are macrotasks, and promise callbacks run between them.

The async variants fix it. Vitest's docs say vi.advanceTimersByTimeAsync "will include asynchronously set timers": it lets promise callbacks run between timers. Each of advanceTimersByTime, advanceTimersToNextTimer, runAllTimers and runOnlyPendingTimers has an Async version. In a React test, wrap it in async act:

TSX
await act(async () => {
  await vi.advanceTimersByTimeAsync(3000);
});

user-event and Testing Library under fake timers

Both were built around Jest's fake timers, and that shows under Vitest:

  • user-event pauses between inputs with setTimeout (the delay option, 0 by default), and under fake timers nothing fires that timeout. Its docs say to pass your clock, userEvent.setup({ advanceTimers: vi.advanceTimersByTime }), and advise against the older delay: null workaround.
  • React Testing Library's async wrapper, which waitFor, findBy and user-event calls all go through, ends with a short setTimeout that it advances only when it detects Jest's fake timers. Under Vitest's fake timers these calls can hang until the test times out, even with advanceTimers set. It is an open issue in the React Testing Library repository.

The dependable pattern: keep tests that need fake timers synchronous, with fireEvent for the interaction, act(() => { vi.advanceTimersByTime(...); }) to move time and getBy to assert. Give tests that need user-event and findBy real timers. vi.useFakeTimers({ shouldAdvanceTime: true }) also unblocks them, but then real time leaks into the fake clock. Vitest's own vi.waitFor, vi.waitUntil and expect.poll do advance fake timers while they wait.

Turn fake timers on before the code under test schedules anything, usually before render. A timer created with the real setTimeout stays real.

SeniorPitfalls

Why tests flake

A passes and fails on the same code. Martin Fowler calls non-deterministic tests useless and "a virulent infection that can completely ruin your entire test suite": once people learn that red sometimes means nothing, they rerun failures instead of reading them, and real bugs get through.

A test flakes when its result depends on something it does not control. The usual suspects:

  • Timing. Fixed sleeps, assertions that run before async work finishes, timeouts that fit a laptop but not a busy CI machine, animations still running.
  • State shared between tests. Vitest gives each test file its own environment, and tests inside a file run one after another, sharing module state, the DOM if cleanup is missing, mocks unless restoreMocks or manual restores reset them, stubbed globals and browser storage.
  • Order dependence. A test passes only because an earlier one created the data it needs, or fails only after one that leaves something behind.
  • The real network. Responses are slow, servers are down, rate limits kick in, data changes.
  • Randomness. Math.random(), generated ids, random test data without a fixed seed.
  • Dates and time zones. "Today", the end of the month, daylight saving time, the machine's time zone.
  • Leaks. A timer or request from one test fires during the next.
  • Shared resources. Files running in parallel use the same port, file or database.

A time zone flake

TypeScript
export function formatDueDate(iso: string) {
  return new Date(iso).toLocaleDateString("en-GB");
}

test("formats the due date", () => {
  expect(formatDueDate("2026-03-01T22:30:00Z")).toBe("02/03/2026");
});

On a laptop in Baku (UTC+4) the instant is 02:30 on 2 March, and the test passes. On a CI runner in UTC it is 22:30 on 1 March, the function returns "01/03/2026", and the test fails. Nobody changed any code. The fix starts with a product decision: which zone does the due date belong to? Then pass it explicitly, toLocaleDateString("en-GB", { timeZone: "Asia/Baku" }), and the result no longer depends on the machine. Running the suite with a fixed TZ makes every machine agree, but it also hides bugs that real users in other zones would see.

Not every flake is the test's fault

Sometimes the test is right and the product has a race: a double submit, an effect that runs after unmount, two requests that finish in either order. Before calling a test flaky, check that the failing result could not happen to a user.

SeniorConcept

Finding a flaky test

A flaky failure in CI is hard to debug if you cannot reproduce it. Make it fail on demand first.

Run it many times

Shell
vitest run src/cart.test.ts --repeats=50

--repeats runs every test that many extra times, and a failure in any run fails the test. One test can also set { repeats: 50 } in its options while you debug it. A test that fails 2 times out of 50 is now something you can work on.

Change the order

Shell
vitest run --sequence.shuffle
vitest run --sequence.shuffle --sequence.seed=1234

Shuffling runs files and tests in random order, which exposes tests that depend on another test running first. The seed decides the order. Pass your own seed and change it between runs; when one fails, run again with the same seed to replay that order while you fix it.

Two quick experiments narrow it down:

  • Run the test alone with -t "adds an item". If it passes alone but fails with its file, another test leaves state behind. If it fails alone but passes in the file, it depends on something an earlier test set up.
  • Run it with its neighbours in a different order, then halve the file until the culprit is clear.

Recreate CI conditions

  • Time zone and clock: TZ=UTC vitest run, and vi.setSystemTime for date edge cases such as month ends.
  • Load: CI machines are slower and run many workers. Try fewer workers or --no-file-parallelism to see if parallel files fight over a shared resource, and a loaded machine to expose timing assumptions.
  • Leaks: --detectAsyncLeaks reports timers and other async resources a test file left running. It makes tests much slower, so use it only while debugging.

Read the evidence

Look at what the failure actually says: which assertion, which value, at what time. Compare several failing runs. If the failure always shows the same wrong value, look for state or data; if it shows "Unable to find" or a timeout, look for timing. A pattern across runs often points at the cause faster than reading the code.

SeniorConcept

Fixing flaky tests instead of retrying them

Once you know the cause, the fix is usually mechanical:

CauseFix
Fixed sleep, assertion too earlyWait for a condition: findBy, waitFor, expect.poll
State left by another testReset in beforeEach/afterEach; restoreMocks, unstubGlobals, cleanup; fresh data per test
Real networkMock it at the network or module level
Clock and time zonevi.setSystemTime; an explicit timeZone in the code
RandomnessInject or seed the generator; assert on properties, not exact values
Leaked timers or requestsFix the code: clear timers and abort requests on cleanup

Each fix makes the test control something it used to depend on. If the cause turns out to be a race in the product, fix the product; the test was right.

Retries are a last resort

TypeScript
export default defineConfig({
  test: { retry: 3 },
});

A global retry turns red builds green and teaches nothing. It hides real races from you while users still meet them, makes failing suites slower, and every retried test still costs time. If something outside your control really is unreliable, such as an external service in an end-to-end run, limit the retry to it. retry can also be an object with count, delay and a condition regex, so only matching errors are retried:

TypeScript
retry: { count: 2, condition: /ECONNREFUSED/ }

Quarantine

Martin Fowler's advice is to move non-deterministic tests to a quarantine, out of the main pipeline, "but fix quarantined tests quickly". He suggests a limit, such as a small number of tests or a week at most, so quarantine does not become a graveyard. Vitest's test tags give you a simple way: mark the test with a flaky tag defined in the config, and run the main suite with vitest --tags-filter="!flaky".

TypeScript
test("syncs the cart", { tags: ["flaky"] }, async () => {
  // ...
});

A plain test.skip works too, if it comes with a linked issue and an owner. Either way, a quarantined test is a known bug with a deadline, not a decision to stop testing.

SeniorInterview tips

Interview tips

A 30-second answer. "An async test must wait for the work it checks: await everything, use findBy or waitFor instead of sleeps, and never put side effects in waitFor. The act warning means a state update happened that the test did not wait for. Fake timers make time-based code fast and deterministic, but with promises you need the async variants. Flaky tests come from timing, shared state, order, the network, randomness and the clock. I reproduce them with repeats and shuffled order, fix the cause, and use retries or quarantine only as a short-term measure."

Questions you are likely to get

  • Why does this test pass when the code is broken? A promise nobody awaits or returns; show the fix and expect.hasAssertions().
  • How does waitFor work? Runs the callback at once, then every 50 ms and on DOM changes, until it stops throwing or 1000 ms pass; the callback must throw to be retried.
  • What does the act warning mean and how do you fix it? An update outside any act scope; wait for the resulting UI with findBy instead of adding act around everything.
  • How do you test a 5-second timeout? Fake timers, advance to 4999 and 5000 ms, assert both sides.
  • A test fails once in 20 CI runs. What do you do? Reproduce with --repeats and --sequence.shuffle, run it alone, match CI's time zone and load, then fix the cause.
  • Should we turn on retries? Not globally; explain what they hide and when a narrow retry is acceptable.

Mistakes that cost points

  • "Add a setTimeout of 1000 ms" or "increase the timeout" as the first idea.
  • Wrapping everything in act to silence the warning.
  • Not knowing why advanceTimersByTime does not run code after an await.
  • Treating flakiness as bad luck rather than a bug in the test or the product.

Senior signal

Talk about the suite as a system. Measure flakiness from CI history, not memory. Make the main branch stay trustworthy: quarantine with an owner and a deadline, a lint setup that catches floating promises and un-awaited queries, cleanup and restoreMocks in config, CI that runs in a known time zone. And point out that some flakes are product races worth fixing for users, not just for the build.

JuniorReview checklist

What to check when reviewing async tests

Use this list on async tests you did not write: a teammate's pull request, a library's example, an AI assistant's suggestion. An async test that does not wait correctly either passes without checking anything or fails at random, and both cost more later than they save now.

  • Is every promise awaited or returned? Look for .then( without return, user. and findBy calls without await, and waitFor without await. Remove the code under test and run the test: it must fail.
  • Does the test wait for a condition, not a fixed time? A setTimeout pause or a raised timeout to make a test pass means it races the code; it should use findBy, waitFor or expect.poll instead.
  • Is waitFor used only for assertions? No clicks, renders or requests inside the callback, one assertion per callback, and never an empty callback.
  • Are fake timers set up and torn down correctly? Turned on before render, restored in afterEach, the Async variants used where promises are involved, and no findBy, waitFor or user-event call left waiting on Vitest's fake clock.
  • Does each test create the state it needs? No reliance on data from another test; mocks, globals and the DOM reset between tests. Run the file with --sequence.shuffle to check.
  • Are time, time zone, randomness and the network under the test's control? vi.setSystemTime, an explicit timeZone, a seeded or injected random source, mocked requests. Run once with TZ=UTC if your team works in another zone.
  • Does every retry or skip have a reason? A narrow condition or a linked issue with an owner; a global retry hides real problems.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    4 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    7 questions