Flaky Tests & Isolation — Testing

A flaky test sometimes passes and sometimes fails with no code change, because it depends on something outside its control: randomness, time, shared state…

Your CI is red. You run the job again, and now it's green. Not a single line of code changed.

A test like that is called a flaky test: it sometimes passes and sometimes fails with no code changing. The cause is always something the test doesn't control: random numbers, time, data left behind by another test, or the network. Picture a smoke alarm that sometimes goes off when you're only boiling water. A week later nobody reacts when it goes off. Then one night there's a real fire, and everyone stays asleep. In this picture, the alarm is your test. The alarm going off for boiling water is a test that fails while the code is fine, and the real fire is a real bug. A CI that's often red from flaky tests is the same: the team gets used to saying "oh, it's flaky, just run it again", and real bugs are missed too.

Why a test can be flaky

The most common causes:

How to spot one: run the same test many times. A healthy test passes 100%. A flaky test has a pass rate between 0 and 100%.

A random source: inject it from outside

The counter below adds to value only when Math.random() (a random number between 0 and 1) is above 0.5:

// Flaky: the result depends on Math.random()
function createCounter() {
  return {
    value: 0,
    increment() {
      if (Math.random() > 0.5) this.value = this.value + 1;
    },
  };
}

Say a test calls increment() three times and expects value to be 3. Out of 100 runs, roughly how many pass? Guess a number first.

Each increment() has a 1/2 chance of adding. For value to reach 3, all three must be lucky: 1/2 × 1/2 × 1/2 = 1/8, about 12.5%. So out of 100 runs, only about 12 or 13 pass.

The fix: the random source is injected, which means it is given from outside as a parameter. The real code passes Math.random, and the test passes a function whose answer is fixed. RNG in the code below is short for random number generator, a function that makes random numbers.

function createCounter(rng) {
  return {
    value: 0,
    increment() {
      if (rng() > 0.5) this.value = this.value + 1;
    },
  };
}

function deterministicTest() {
  const counter = createCounter(() => 0.9); // the RNG is always 0.9, always > 0.5
  counter.increment();
  counter.increment();
  counter.increment();
  return counter.value;
}

console.log(deterministicTest()); // 3

Shared state: beforeEach makes a fresh one

In this example, one shopping cart, cart, is made once and used by two tests:

let cart = createCart(); // made once, used by every test

it("adds one item", () => {
  cart.add("Book");
  expect(cart.size).toBe(1);
});

it("starts empty", () => {
  expect(cart.size).toBe(0);
});

In the normal order, the second test ("starts empty") always fails: expected 1 to be +0, because the Book from the first test is still in the cart. You can shuffle the order with npx vitest run --sequence.shuffle, and Vitest then writes the seed, for example Running tests with seed "3". When the order is shuffled, the second test sometimes runs first, and both pass. The result depends on the order, so this test is flaky.

The fix: every test gets a fresh cart. This is called test isolation: every test starts from its own state, so its result doesn't depend on other tests or on their order.

let cart;
beforeEach(() => {
  cart = createCart();
});

In Laravel, the RefreshDatabase trait does the same for the database: every test starts from a clean database.

Time: don't guess durations

The test below guesses that 100 ms is enough to load the data:

it("shows the data once it's loaded", async () => {
  loadData();                                    // takes 40 to 160 ms
  await new Promise((r) => setTimeout(r, 100));  // a guess: 100 ms is enough
  expect(status).toBe("done");
});

When the network is slow, 100 ms isn't enough: expected 'loading' to be 'done'. The fix: wait for the process itself, not the clock. You do that with await loadData(), or with await screen.findByText(...) in a component test. For timers in the code, use vi.useFakeTimers() then vi.advanceTimersByTime(1000). For dates, use vi.setSystemTime(new Date("2025-01-15")). For a real server, use a mock such as MSW in its place.

Retry: a temporary measure, not a fix

Retry means running a failed test again automatically. Vitest and Playwright can do it:

it("async operation", { retry: 3 }, async () => {
  // ...
});

{ retry: 3 } means a failed test may be run again up to three times. If the test passes on the third attempt, which is the second retry, the report says ✓ ... (retry x2), and CI is green. The problem is that retry hides the root cause without fixing it. The timing problem, the shared state or the network problem stays, and a real bug that appears now and then gets hidden too. Use retry only for things outside your control (for example, a CI network that sometimes drops), note which test it is, and fix the root cause. To make sure a test is stable, run it many times, for example npx playwright test --repeat-each=20.

⚠️ Habits that make tests flaky

TL;DR: A flaky test sometimes passes and sometimes fails with no code change, because it depends on something outside its control: randomness, time, shared state (data that several tests use), or the network. Fix the root cause. Inject the random source as a parameter, for example the random function rng in createCounter(rng), which the test replaces with () => 0.9 (a function that always answers 0.9). Make fresh state in beforeEach, wait for the process itself or use fake timers, and mock the network. Retry (running a failed test again) isn't a fix, because it hides the root cause without fixing it. Spot flaky tests by running them many times: a healthy test passes 100%.

⚡ What a flaky test is

Meaning: A flaky test sometimes passes and sometimes fails with no code change. The cause is something the test doesn't control: randomness, time, shared state (data that several tests use), or the network. To spot one, run it many times. A healthy test passes 100%.

⚡ Inject the random source from outside

Write:

function createCounter(rng) {
  return {
    value: 0,
    increment() {
      if (rng() > 0.5) this.value = this.value + 1;
    },
  };
}

const counter = createCounter(() => 0.9);
Guess first: rng() is replaced by Math.random() (a random number between 0 and 1). A test calls increment() three times and expects value to be 3. How many of 100 runs pass?

Only about 12 or 13. All three increment() calls must add, and each has a 1/2 chance: 1/2 × 1/2 × 1/2 = 1/8.

Meaning: increment() adds to value only when rng() gives a number above 0.5. The function rng is injected, which means it is given from outside as a parameter. In the app, call createCounter(Math.random). In the test, () => 0.9 is always above 0.5, so the result is always 3.

⚡ Shared state: beforeEach makes a fresh one

Write:

let cart;
beforeEach(() => {
  cart = createCart();
});

Meaning: beforeEach runs createCart() before every test, so every test gets a fresh cart. Data from an earlier test doesn't carry over, and the order of the tests no longer decides the result. This is called test isolation.

⚡ Retry is not a fix

Meaning: Retry (running a failed test again automatically) turns CI green, but hides the root cause without fixing it. Use retry only for things outside your control, then fix the root cause.

What you will learn