Skip to content
mentoor

Topic 5 of 5 · 5 min read

Flaky tests, fixtures and determinism

Goal: Find the source of non-determinism in a flaky test and fix it instead of adding a retry or a skip.

A flaky test passes and fails on the same code. Find the hidden input that changes between runs, remove it, and never hide the flake with a retry or a skip. Flakiness is a bug in the test or in the code, and both deserve a fix.

Check yourself · 1 of 3

What defines a flaky test?

Choose one answer

Why it matters

A flaky suite teaches the team to ignore red builds. Then a real failure gets rerun until it turns green and ships. Agents make this worse. Faced with a failing CI job, an agent's cheapest moves are to add a retry, increase a timeout or mark the test as skipped. The build goes green, the cause stays, and the flake comes back somewhere else.

The usual sources

Look for an input the test does not control:

  1. Time. Date.now(), the current day, time zones, daylight saving, a test that crosses midnight. Fix: inject a clock or freeze time.
  2. Randomness. Random ids, shuffled lists, generated data. Fix: seed the generator and log the seed.
  3. Order and shared state. Tests that share a database row, a global variable, a file or a cache. Fix: each test builds and cleans its own data.
  4. Async timing. Asserting before a promise, a queue or a render has finished. Fix: wait for the condition, never for a fixed time.
  5. The network. Real calls to a service that is slow or down. Fix: fake the service, or use a local one you control.
  6. The environment. Different CPU speed, ports already in use, a locale. Fix: use free ports and pin the settings.

How to find it

Run the single test in a loop, for example fifty times, and note the failure rate. Run it alone, then with its neighbours in random order. If it fails only in the full suite, suspect shared state. If it fails only on slow machines, suspect timing. Record the seed, the time and the logs of each failing run.

Before and after

// Flaky: depends on the real clock
test("token is valid for an hour", () => {
  const t = createToken();
  expect(isValid(t)).toBe(true);
});

Fixed with a controlled clock:

test("token expires after an hour", () => {
  vi.useFakeTimers({ now: new Date("2026-03-01T10:00:00Z") });
  const t = createToken();
  vi.setSystemTime(new Date("2026-03-01T11:00:01Z"));
  expect(isValid(t)).toBe(false);
});

What goes wrong

  • Retries as a cure. Three attempts hide a one-in-three failure and slow every run.
  • Quarantine forever. A skipped test is not tracked, and nobody comes back.
  • Longer timeouts. They move the failure from fast machines to slow ones.
  • Blaming CI. The environment exposes the race; it did not create it.

Examples

The midnight test

def test_daily_report_uses_today():
    report = build_report()
    assert report.date == date.today()

It fails if the clock passes midnight between the two calls. Pass the date in, or freeze time, and assert against a fixed day.

The agent adds a retry

CI shows an order test failing one run in five. The agent adds retries: 3 and the build is green. The real cause is two tests inserting the same email address into a shared table. The retry hides the collision; unique emails per test remove it.

Key points

  • A flaky test has a hidden input that changes between runs: time, randomness, order, shared state, timing or the network.
  • Run the test many times, alone and in random order, to see which kind of flake it is.
  • Fix the cause by injecting a clock, seeding randomness, isolating data or waiting on conditions.
  • A retry, a longer timeout or a skip hides the flake and leaves the bug.
  • Tell agents explicitly not to add retries or skips to make CI green.

Common mistakes

  • Adding retries, longer timeouts or skips instead of finding the changing input.
  • Rerunning a red build until it passes and merging.
  • Letting tests share a table, file or global state and depend on running order.
  • Using real network calls or the real clock in tests that must be repeatable.

Check yourself · 2 of 3

A test builds a token and then checks it is valid for one hour, using the real system clock. Which fix removes the non-determinism?

Choose one answer

Check yourself · 3 of 3

CI shows a test failing about one run in five. An agent proposes adding a retry of three attempts. What is the best response?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic