Skip to the page

Keeping tests useful · senior

Flaky tests: causes and real fixes

A flaky test passes and fails on the same code; the causes are almost always timing, shared state, order dependence, real network or time, or environment differences, and the fix is to remove the non-determinism, not to add sleeps or blind retries.

The notes

What you must know

  • Timing: fixed sleeps, not awaiting async work, animations. Fix: wait for conditions (findBy, web-first assertions), fake timers, disable animations in tests.
  • Shared state and order: module-level variables, unrestored mocks/spies, leftover DB rows, localStorage. Fix: reset in beforeEach/afterEach, fresh contexts, unique test data, run tests in random order to find these.
  • External dependencies: real APIs, third parties, DNS. Fix: MSW / page.route, or a stable test environment.
  • Time and randomness: Date.now, time zones, Math.random, locales. Fix: fake timers, setSystemTime, fixed TZ and locale in CI, seeded random.
  • Process: detect flakes (Playwright marks a test 'flaky' when it passes on retry), quarantine with an owner and a ticket, fix within a deadline, track a flake-rate metric. Retries hide pain; use them to detect, not to forget.
  • Parallelism: tests that share a resource (same user account, same port) collide; give each worker its own data.

The red pen

Common traps: mistake → fix

  • Mistake: "Increase the timeout / add a sleep"

    Fix: the race still exists; it fails less often and the suite gets slower.

  • Mistake: "Retries fixed it"

    Fix: retries hide the flake and real intermittent bugs in the product.

  • Mistake: "It only fails in CI, so CI is broken"

    Fix: CI is slower and parallel; it exposes real races in tests or code.

Easy to hard

Questions interviewers ask, easy to hard

  1. What causes flaky tests? Give examples from your experience.
  2. How do you find and fix an order-dependent test?
  3. How does your team handle flaky tests in CI?
  4. A Playwright test fails 5% of the time only in CI. Walk me through your investigation.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview