StoicBuilder

HandbookVIII the PalaestraFlaky tests

VIIIthe Palaestra, Test it

Flaky tests

1 min readUpdated 28 November

In plain words

A flaky test passes on one run and fails on the next with identical code, usually because it depends on timing, test order, today's date or a network call.

Where you see it

Harbor's CI goes red on the invoice-download test about one run in five, someone clicks Re-run, and it goes green. A month later the team re-runs every failure without reading it, including the one that was real.

e2e/invoices.spec.tsbrowser
// flaky: guesses how long the PDF takesawait page.getByRole("button", { name: "Download invoice" }).click();await page.waitForTimeout(2000); // steady: waits for the event itselfconst downloadPromise = page.waitForEvent("download");await page.getByRole("button", { name: "Download invoice" }).click();const download = await downloadPromise;
A fixed sleep fails whenever the server is slower than the guess. Waiting for the download event finishes as soon as it happens.

What goes wrong

  1. Fixing it with a longer sleep

    Raising the wait from 2 to 5 seconds makes the failure rarer and every run slower. Wait for the thing you need instead: a response, an element, a download.

  2. Tests that depend on today's date

    A test that expects the next invoice on the 31st fails in every month with 30 days. Freeze the clock in tests, for example with vi.useFakeTimers() and vi.setSystemTime().

  3. Retrying until green and moving on

    Automatic retries hide the problem and teach the team to ignore red. Quarantine a flaky test with a ticket and an owner, and fix or delete it within days.

What to tell your agent

Copy this into Lovable, Bolt, Cursor or any agent
This test fails about one run in five. Run it 20 times in a row (in Playwright, with --repeat-each=20), work out what it depends on (timing, order, date or network) and fix that cause. Don't add sleeps, longer timeouts or retries.

Quick check

Sign in to earn +10 XP for it

A Harbor test fails about once a week with a timeout. The agent proposes raising the timeout from 5 to 30 seconds. What's the better move?

Got a prompt that touches flaky tests?

Paste it. You get a better prompt first, then the cards that explain it.

Check your own prompt

Free, no sign-up.