Flaky Tests: How to Detect, Debug, and Fix Them
Flaky Tests: How to Detect, Debug, and Fix Them
A flaky test passes and fails on the same code. Most flakiness comes from timing, shared state, test order, unstable data, or the environment. Detect it with rerun statistics, debug it with traces and repeated local runs, and fix the cause instead of adding retries.
It’s the one problem every team running automated testing hits eventually, and the one most likely to quietly destroy trust in a suite that cost real money to build.
Google’s definition from its testing blog is still the clearest one: “a test that exhibits both a passing and a failing result with the same code.” Everything below was run on Playwright 1.65.1, and where we quote a failure rate, we measured it.
What Makes a Test Flaky
| Cause | Symptom | Typical fix |
|---|---|---|
Fixed waits | Fails on slow CI, passes locally | Web-first assertions that retry |
Shared state | Fails when run with others, passes alone | Fresh data per test |
Order dependence | Fails in parallel, passes at --workers=1 | Remove module-level state |
Unstable test data | Fails on the second run of the day | Unique data per test run |
Real network calls | Fails when a third party is slow | Mock the boundary |
Async UI | Fails on animations, toasts, lazy loads | Assert on the end state |
Environment | Fails only in CI | Pin versions, time zone, locale |
Brittle selectors | Fails after any markup change | Role-based locators |
That last row is a different problem with a different fix, and we’ve covered it separately in self-healing test automation. This article is about the other eight — tests that break without anyone touching the markup.
One figure worth keeping in mind. When Google analysed a month of its own CI in 2016, 84% of its pass-to-fail transitions involved a flaky test rather than a real regression. The number is a decade old and from a codebase unlike yours, but the shape of the problem hasn’t changed: most red builds aren’t bugs.
How to Detect Flaky Tests
You can’t fix what you can’t see, and a single run tells you nothing. A flaky test looks exactly like a passing test on the run where it passes.
Run each test many times. Playwright has a flag for it:
npx playwright test –repeat-each=20
Measure a rate, not a verdict. The formula is simple:
flakiness rate = failed runs ÷ total runs (same commit, same environment)
Here’s a real measurement. We wrote one test two ways and ran the suite 20 times against identical code:
| Version | Failures in 20 runs | Flakiness rate |
|---|---|---|
await page.waitForTimeout(150) | 9 | 45% |
await expect(locator).toHaveCount(2) | 0 | 0% |
A 45% flake isn’t subtle, but a 5% one is — and a 5% flake in a 300-test suite still turns most of your builds red.
Make the build fail on flakiness. This flag isn’t in the Playwright docs, but it works:
npx playwright test –retries=2 –fail-on-flaky-tests
Without it, a test that fails then passes on retry exits 0 and your pipeline stays green. With it, the run exits 1. We checked both.
Tag what you’ve found. Playwright takes a tag as the second argument, and the reporter shows it:
test(‘checkout with a saved card’, { tag: ‘@flaky’ }, async ({ page }) => {
// …
});
Then split your pipeline in two. The blocking job skips them, a second non-blocking job still runs them so you keep the signal:
npx playwright test –grep-invert @flaky # blocking job
npx playwright test –grep @flaky # reporting job, never blocks a merge
Quarantine rather than delete. A test nobody trusts is worse than no test, but deleting it silently loses coverage. The rules that make quarantine work — owners, deadlines, caps — are covered in our QAM Hub guide to a flaky test quarantine policy.
Debugging a Flaky Test
The hard part is catching it in the act. These three things do most of the work.
Record a trace on retry. The generated config already does this:
use: {
trace: ‘on-first-retry’,
},
When a test fails and then passes, Playwright keeps a trace of the failing attempt in test-results/<test-name>-retry1/trace.zip. Open it with Trace Viewer:
npx playwright show-trace test-results/orders-flaky-chromium-retry1/trace.zip
You get the DOM at every step, network, console output and timings — for the run that actually failed. For a timing flake, compare the failing trace with a passing one and look at how long the step took.
Keep video and screenshots too. A trace tells you what the page contained; a video shows you what it looked like while it happened, which is faster for animation and focus bugs:
use: {
trace: ‘on-first-retry’,
video: ‘retain-on-failure’,
screenshot: ‘only-on-failure’,
},
Videos are recorded for every test and deleted for the ones that pass, so the storage cost stays bounded. Browser console errors are already in the trace’s Console tab — worth checking first, because an unhandled rejection in the app often explains a “random” failure.
Reproduce it locally. Run the single test in a loop until it fails:
npx playwright test tests/orders.spec.ts –repeat-each=50 –workers=1
If it never fails locally but fails in CI, the cause is environmental — slower machines, different parallelism, different data.
Change the parallelism. This one diagnoses order dependence in a single step:
npx playwright test –workers=1 # passes?
npx playwright test –fully-parallel # fails?
If the answer is yes and yes, your tests share state. We proved this with two tests and a module-level array — green at –workers=1, red in parallel.
Optimize Your Testing Today
Ready to level up your quality? From test automation services to full-scale software testing outsourcing, we help you build a product that is extraordinary.
Fixes by Cause
Each of these takes minutes. Skipping them is what turns a handful of unreliable tests into test automation debt that costs a sprint to pay down.
Replace fixed waits with web-first assertions
This is the single biggest source of flakiness, and the fix is a one-liner.
// Flaky: 45% failure rate in our measurement
await page.getByRole(‘button’, { name: ‘Load orders’ }).click();
await page.waitForTimeout(150);
expect(await page.getByTestId(‘order’).count()).toBe(2);
// Stable: 0% across the same 20 runs
await page.getByRole(‘button’, { name: ‘Load orders’ }).click();
await expect(page.getByTestId(‘order’)).toHaveCount(2);
The second version retries until the condition holds or the timeout expires. The first bets that 150ms is always enough. On a loaded CI runner, it isn’t.
Remove shared state
// Order-dependent: fails the moment these run in parallel
let cart: string[] = [];
test(‘adds an item’, async () => {
cart.push(‘A-1001’);
expect(cart).toHaveLength(1);
});
test(‘cart has one item’, async () => {
expect(cart).toHaveLength(1); // only passes if the test above ran first
});
Each test should set up everything it needs. Use a fixture for shared setup — a fixture runs per test, a module-level variable doesn’t.
The same applies to states outside the test file. If a test changes a user’s settings, a feature flag or a database row, reset it in the fixture’s teardown rather than hoping the next test doesn’t care. Shared backend state is the version of this bug that survives every frontend refactor.
Give each test its own data
Two tests registering [email protected] will collide, and so will the same test run twice. Playwright gives you a unique value per test:
test(‘registers a new user’, async ({ page }, testInfo) => {
const email = `user-${testInfo.testId}@example.com`;
// …
});
Use testInfo.outputPath() for the same reason when tests write files.
Mock the boundary
A test that calls a real payment sandbox fails when that sandbox is slow. If you’re testing your checkout UI rather than their API, intercept it:
await page.route(‘**/api/payments’, route =>
route.fulfill({ json: { status: ‘approved’, id: ‘pay_123’ } })
);
Keep a small number of genuine integration tests and run them separately, where a third-party outage doesn’t block a merge.
Wait for the end state, not the animation
Toasts, modals and lazy-loaded lists are mid-flight for a moment. Asserting during that moment is a coin flip.
// Flaky: the toast is still fading in
await page.getByRole(‘button’, { name: ‘Save’ }).click();
await expect(page.locator(‘.toast’)).toHaveText(‘Saved’);
// Stable: wait for the state that actually matters
await page.getByRole(‘button’, { name: ‘Save’ }).click();
await expect(page.getByRole(‘status’)).toHaveText(‘Saved’);
await expect(page.getByRole(‘button’, { name: ‘Save’ })).toBeEnabled();
If an animation really does get in the way, turn it off for the test run rather than sleeping through it. Playwright can disable CSS animations when it takes screenshots, and most design systems respect prefers-reduced-motion.
Pin the environment
A test that passes in Kyiv and fails in CI is often reading the clock or the locale. Set both in config so every machine agrees:
// playwright.config.ts
use: {
timezoneId: ‘Europe/Kyiv’,
locale: ‘en-GB’,
},
Dates are the usual culprit. A test asserting 01/02/2026 means 1 February in one locale and 2 January in another, and it’ll pass on your laptop right up until it runs somewhere else.
Are Retries OK?
Retries are fine as a measurement tool and dangerous as a fix.
Useful, because they tell you a test is flaky. Playwright’s retry handling sorts every result into three buckets: passed on the first run, flaky (failed first, passed on retry), or failed. That middle bucket is your worklist.
// playwright.config.ts
retries: process.env.CI ? 2 : 0,
Zero retries locally so you see problems immediately, two in CI so one bad run doesn’t block a merge.
Dangerous, because retries hide real bugs. A race condition in your application is intermittent too, and a retry makes it look like a flaky test. Three rules keep that honest:
- Cap it at two. If a test needs three attempts, it isn’t flaky, it’s broken.
- Never retry silently. The flaky count has to be visible, or nobody acts on it.
- Treat a rising flaky count as debt. Like any other kind, it’s cheap to ignore for a quarter and expensive after that.
Using AI to Triage Flaky Failures
With a few hundred tests, flaky triage becomes a job nobody wants: open the failure, read the trace, decide whether it’s a flake, a bug or the environment. That decision is mostly pattern-matching, which is work an AI agent is well suited to.
What matters is the signals you collect for every failed run:
- The error message and stack trace
- The failing step and its trace file
- Screenshot or visual diff at the point of failure
- The rerun result — did it pass on retry?
- Recent commits touching the code under test
- Whether other tests failed in the same run
From those, a failure sorts into one of three labels. Flake — passed on retry, no related code change, timing-shaped error. Bug — fails consistently, correlates with a recent commit. Environment — many unrelated tests failed together, or the error is a connection refusal rather than an assertion.
The rule we hold to: a human approves before a bug is filed. The agent proposes a label and the evidence for it; an engineer confirms. Auto-filing is how a flaky test becomes a ticket that wastes a developer’s afternoon, and how a real regression gets closed as “flaky” and shipped.
Our AI-augmented testing services include this triage loop, with CI/CD monitoring and flakiness detection as part of the workflow. For the wider picture of fitting AI into a QA process you already have, see our AI-powered QA integration guide.
Tracking Flaky Tests Over Time
Most dashboards track flakiness per run. The useful unit is per test, over time.
A run-level number tells you today was bad. A test-level history tells you checkout.spec.ts:42 has failed 14 times in 200 runs over three weeks, always on the payment step, always in CI. The first is a mood. The second is a ticket.
Record four things per test, per run:
- Outcome on the first attempt — before any retry
- Whether a retry rescued it
- Duration, because a flake often shows up as a slow run first
- Environment and branch
From those you get a first-attempt pass rate per test, which is the number worth putting on a dashboard. A test at 99% is fine. A 85% test is costing you more than it’s catching.
Keeping that history is what a test management system is for. QAM Hub’s flaky test detection tracks each test across uploaded runs, and reports pass rate, flaky rate, and a first-attempt stability score, with quarantined tests excluded from the averages so they don’t flatter your numbers.
Get a Suite Your Team Trusts Again
Flaky tests don’t announce themselves. They arrive one retry at a time, until nobody reads the build status and real regressions ship because the build was already red.
Our test automation services cover flakiness as part of suite health: measuring it per test and fixing causes rather than symptoms. Pair that with AI-augmented testing and the triage loop runs continuously, so a rising flaky count reaches someone before it reaches your release. ISTQB-certified QA engineers, working in your stack.
Contact us and we’ll tell you what your flakiness rate actually is.
FAQs
A test that passes and fails on the same code, with no change in between. The result depends on something the test doesn’t control — timing, shared state, test order, external services, or the machine it runs on.
Run the same tests repeatedly against the same commit and count the failures. –repeat-each=20 does it locally. In CI, enable retries so Playwright reports a flaky count, then track that count per test over time rather than per run.
Find the cause first. Replace waitForTimeout with web-first assertions like toHaveCount or toBeVisible, move shared setup into fixtures, give each test unique data with testInfo.testId, and mock third-party calls with page.route. Adding a retry is not a fix.
Retry twice in CI, zero times locally, and never silently. Retries are how you detect and contain flakiness while you fix it — not a permanent state. If the flaky count isn’t visible to the team, retries just hide the problem.
Zero, for any test you’d block a release on. As a practical target, a first-attempt pass rate above 99% per test is healthy. Below about 95%, a test costs more attention than it returns and belongs in quarantine.
For scale: Google reported 1.5% of its test runs returning a flaky result in 2016, across millions of tests and with a dedicated infrastructure team.