Test automation ·
Flaky Tests: Common Causes and How to Fix Them
By The QAcademy team

The pipeline is red. You rerun the job and it turns green. Nobody knows why, and three weeks later the team has stopped looking at failures: "that test is just moody." That is exactly why flaky tests are dangerous. They don't only waste time, they erode trust in the whole suite.
In this article you'll see what a flaky test is, the five causes that come up most often, a method to debug them instead of rerunning them, and concrete fixes in TypeScript with Playwright.
Flaky Tests: What Are We Actually Talking About?
A test is flaky when it passes and fails on the same code, with nothing changed. The Google Testing team put it this way: a flaky result is a test showing both a passing and a failing outcome with the same code (Google Testing Blog). The same post gives an order of magnitude: about 1.5% of test runs at Google were flaky at the time, and almost 16% of tests showed some level of flakiness. Those are numbers from a very large system, not a benchmark. Measure your own.
Two myths to drop right away:
- Flaky doesn't mean "unimportant." An intermittent test can hide a real concurrency defect in the product. Deleting it without understanding it can mean switching off the alarm.
- Rerunning is not fixing. A retry hides the symptom. It is a useful safety net, never an answer.
The 5 Most Common Causes
1. Poorly handled waiting (timing)
The classic: the test acts or asserts before the application is ready. Fixed pauses (sleep, waitForTimeout) are the worst remedy: too short on slow days, too long the rest of the time.
2. Shared or drifting data
Two tests use the same account, order or database row. Depending on execution order, one breaks the other's state. Tests pass alone and fail in parallel.
3. An unstable environment
A slow third-party service, a staging database shared with other teams, a container that starts late, a saturated CI runner. The test is right, the environment isn't.
4. Order and leftover state
A test depends on state left by the previous one (cookie, file, cache, feature flag). It passes in the usual order and fails as soon as you reorder or run it alone.
5. Time, randomness and dynamic values
Today's date, time zones, generated IDs, non-deterministic sorting: the expected result changes with the moment or the random seed.
| Cause | Typical symptom | First lead |
|---|---|---|
| Waiting | Fails mostly in CI, never locally | Replace fixed pauses with condition-based waits |
| Data | Fails in parallel, passes alone | Unique data per test |
| Environment | Clustered failures, network errors | Isolate or stub the dependency |
| Order | Fails when order changes | Reset state before each test |
| Time / randomness | Fails at certain hours or dates | Freeze or inject the clock and the seed |
An Illustrative Scenario
Imagine an insurance claims application. An end-to-end test creates a claim, saves it, then checks that the message "Claim saved" appears. It fails one run in ten in CI.
The test clicks, waits a fixed two seconds, then reads the message. Locally the API answers in 300 ms. In CI, on a shared machine, it sometimes takes 2.5 s. Meanwhile a second test reuses the same contract number: if it runs first, the claim already exists and saving is rejected. Two causes, one symptom. That is typical: a flaky test rarely has a single cause.
Debug Before You Fix
Here is a method that avoids guessing:
- Reproduce in a loop. Run the test alone 20 to 50 times. If the failure only shows up in the full suite, you've just ruled out pure timing and pointed at order or data.
- Change one variable at a time: alone, in parallel, in random order, on another machine.
- Capture evidence. Keep traces, screenshots and logs from the failure, not only from the pass. Playwright's retries distinguish three outcomes: passed, flaky (failed, then passed on retry) and failed (Playwright docs). That "flaky" status hands you a suspect list for free.
- Look for what differs between a pass and a failure: response time, data present, time of day, order.
Fixing: Three Concrete Examples
Replace the fixed pause with an assertion that waits
Playwright checks several conditions before acting on an element (visible, stable, enabled, able to receive events, per the actionability docs). Its web assertions (expect(locator)…) retry until the timeout. Lean on them.
import { test, expect } from '@playwright/test';
test('saving a claim shows the confirmation', async ({ page }) => {
await page.goto('/claims/new');
await page.getByLabel('Contract number').fill(`CT-${Date.now()}`);
// ❌ Avoid: a fixed pause is fragile and slow
// await page.waitForTimeout(2000);
// expect(await page.getByRole('status').textContent()).toBe('Claim saved');
await page.getByRole('button', { name: 'Save' }).click();
// ✅ The assertion retries until the condition is true (or times out)
await expect(page.getByRole('status')).toHaveText('Claim saved');
});
Give every test its own data
In the example above the contract number is unique (CT- + timestamp), so two parallel tests no longer step on each other. For richer data, create it through the API before the test and delete it afterwards, instead of sharing a common dataset.
Keep retries as a safety net, not a cure
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
// 2 retries on CI only: they show up as "flaky" in the report,
// and they don't hide the problem on your machine
retries: process.env.CI ? 2 : 0,
});
A test that passes on retry still needs work: open a ticket with a due date. If you quarantine a test (remove it from the critical path), give it an owner and a review date, or the quarantine becomes a graveyard. Google describes the same trade-off: automatic isolation reduces noise but can mask a real race condition.
Prevent: A Few Team Habits
- Treat a flaky test as a bug, with a ticket and an owner, not as fate.
- Track one simple indicator: the share of tests that only pass on retry, week after week. If it climbs, that's your signal.
- Keep end-to-end tests few and push checks down to lower levels (unit, API), which are faster and less exposed to UI timing.
- Review AI-generated tests with the same rigor: a script produced by an assistant happily contains fixed pauses and brittle selectors. Our article on generating test cases with AI shows how to frame that work.
- If the unpredictability comes from the product itself, for example a non-deterministic LLM output, the logic changes: read testing LLM applications.
Key Takeaways
- A flaky test passes and fails on the same code: it's a signal to understand, not noise to rerun.
- The dominant causes: poor waiting, shared data, unstable environment, execution order, time and randomness.
- Diagnose first: replay in a loop, change one variable at a time, keep the traces of failures.
- Replace fixed pauses with condition-based waits and give each test its own data.
- Retries and quarantine are safety nets, with an owner and a deadline.
FAQ
What is a flaky test?
An automated test whose result changes (pass or fail) while the code under test hasn't. The cause can sit in the test, the environment or the product.
How do you fix a flaky test?
Reproduce the failure by running the test many times, find what differs between a pass and a failure, then address the cause: condition-based waits instead of fixed pauses, isolated data, reset state, controlled clock.
Should I use retries to avoid flaky tests?
Retries reduce CI noise but fix nothing. Use them sparingly, watch the tests that only pass on retry and treat them as defects to fix.
Sources
- Flaky Tests at Google and How We Mitigate Them, Google Testing Blog.
- Test retries and Auto-waiting (actionability), Playwright documentation.
What's Next?
Want to know where you stand on testing fundamentals before scaling your automation? Take the free diagnostic: 10 questions, about 5 minutes. And if you'd rather follow new articles by email, QAcademy sends a weekly newsletter (at most one email a week, one-click unsubscribe).
Take the next step
You have just read. Now see where you stand: 10 questions, your score chapter by chapter, free and without signing up.
Take the free test (5 min)Already decided to practise?
- Complete Pack, €149 : the full course (5 chapter sheets, 9 labs), the chapter quizzes, plus the mock exams
- Exam Pack, €39 : 2 full mock exams, with a detailed review of every option
One-off payment, no subscription, refunded within 14 days if it is not for you.
Get the new articles by email
At most one email a week: the new QAcademy articles on software testing and quality. Free, unsubscribe in one click.