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?
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:
- Time.
Date.now(), the current day, time zones, daylight saving, a test that crosses midnight. Fix: inject a clock or freeze time. - Randomness. Random ids, shuffled lists, generated data. Fix: seed the generator and log the seed.
- 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.
- Async timing. Asserting before a promise, a queue or a render has finished. Fix: wait for the condition, never for a fixed time.
- The network. Real calls to a service that is slow or down. Fix: fake the service, or use a local one you control.
- 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?
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?
Practice items, not counted towards your mastery.
Start here
- The Practical Test Pyramid (martinfowler.com) (opens in a new tab)ArticleFree
Walks through unit, integration and end-to-end levels with code, and why to push tests to the lowest level that catches the bug.
- Software Engineering at Google (free online book) (opens in a new tab)BookFree
The testing chapters cover test size, flakiness and what a useful test suite looks like at scale.
- Playwright documentation (opens in a new tab)DocsFree
How to write and run browser tests with auto-waiting, the basis for stable end-to-end flows.
More for this topic
- Non-Deterministic Tests (Martin Fowler) (opens in a new tab)ArticleFree
Names the usual causes of flaky tests (shared state, async, remote services) and how to remove each.
- Flaky Tests at Google and How We Mitigate Them (opens in a new tab)ArticleFree
A large team's account of why flaky tests cost trust and how it tracks and handles them.