Skip to content

Refactor a Flaky Test to Stable

Test AutomationUpdated 2026-10-21advanced
TL;DR

Takes a flaky test and its failure history, identifies which of the canonical root causes (race, hard sleep, shared state, network dependency, ordering, animation) is responsible, and produces a rewritten test that fixes the specific cause: no blanket retries.

When to use it

  • A test fails ~5-30% of the time in CI and you don't know why.
  • You want to root-cause flakiness before deciding to retry or quarantine.
  • You're rewriting a legacy suite with `waitForTimeout` everywhere and want consistent patterns.
  • You want to teach junior engineers how to think about flake causes, not just retry counts.

The prompt

XML-tagged: works best with Claude
refactor-flaky-test.claude.mdprompt
<role>You are a test reliability engineer. You believe retries hide bugs, not fix them. Before rewriting a flaky test, you identify its root cause by category, race, hard sleep, shared state, network dependency, ordering, or animation, and you address THAT cause, not a generic retry.</role> <context>Canonical flake categories:1. **Race**: Test asserts state before the event that produces it completes.2. **Hard sleep**: `waitForTimeout` or thread.sleep guesses at duration; passes on slow CI, fails on fast.3. **Shared state**: Test depends on data/setup left by another test; order-dependent.4. **Network dependency**: Test hits a real external service; intermittent failures.5. **Ordering**: Test runs first or last and behaves differently.6. **Animation / debounce**: Element exists in DOM but isn't actionable yet (mid-animation, debounced handler not flushed).</context> <task>For the test code and failure history I provide:1. Identify ONE canonical root cause from the categories above. Cite the specific signal in the code that maps to it.2. Rewrite the test addressing that cause:   - Race → replace with `expect(locator).toBeVisible()` or similar event-driven wait.   - Hard sleep → replace with auto-waiting expect.   - Shared state → add `test.beforeEach` setup and ensure teardown.   - Network → stub via `page.route()` or Playwright APIRequestContext mocking.   - Ordering → make test fully self-contained (own data, own auth).   - Animation → wait for animation end or use CSS to disable in test mode.3. Explicitly REJECT adding retries (`retries` in the config, `test.describe.configure({ retries })`) unless the cause is truly environmental and not in the test.</task> <input>Test code: {test_code}Failure pattern / history: {failures}Framework version (Playwright X.Y, Cypress X.Y): {framework}</input> <constraints>- Identify exactly ONE root cause; if you see multiple, pick the dominant and note the others.- DIAGNOSIS BEFORE REWRITE: never produce a rewrite without naming the cause.- Do not add retries (config `retries`, `test.describe.configure({ retries })`, `--retries`).- Do not introduce `waitForTimeout` in the fix.- Keep the test's intent identical; reviewers should not see scope changes.</constraints> <output_format>Three sections:1. **Root cause**: Category name + 1-2 sentences citing the line in the original code.2. **Rewritten test**: Code block.3. **Why this fix works**: 2-3 sentences explaining what the change does and why retries weren't needed.</output_format> <approach>Read the test code carefully before declaring a cause.</approach>

Example

Input
Test code:
test('shows search results after typing', async ({ page }) => {
  await page.goto('/search');
  await page.locator('#search-input').fill('playwright');
  await page.waitForTimeout(2000);
  const results = page.locator('.result-card');
  expect(await results.count()).toBeGreaterThan(0);
});

Failure pattern: Fails ~25% of the time on GitHub Actions, never fails locally. Fails with "Expected: > 0, Received: 0". Logs show the request went out and returned 200 with results.

Framework: Playwright 1.62
Output
**Root cause:** Hard sleep (category 2). The test uses `await page.waitForTimeout(2000)` after triggering a debounced search. On slow CI, the debounce + network round-trip + DOM update sometimes exceeds 2 seconds, and `expect(await results.count())` is a one-shot check that never retries, so it reads 0 before `.result-card` elements are rendered.

**Rewritten test:**
```typescript
test('shows search results after typing', async ({ page }) => {
  await page.goto('/search');
  await page.locator('#search-input').fill('playwright');
  // Wait for the debounced fetch + render via the result card itself.
  await expect(page.locator('.result-card').first()).toBeVisible();
  await expect(page.locator('.result-card')).not.toHaveCount(0);
});
```

**Why this fix works:** `expect(locator).toBeVisible()` is a web-first assertion: it retries until the expect timeout (5s by default), polling the DOM until the element appears. This adapts to the actual time the system takes, fast locally, slower on CI, and fails fast if the element truly never appears. No retries needed because the test now waits for the event we care about (a card rendered), not for an arbitrary wall-clock duration.

Common pitfalls

  • Model identifies multiple causes and rewrites ambiguously: force ONE dominant cause.
  • Rewrite keeps a one-shot check like `expect(await locator.count())` after removing the sleep: it never retries, so the race stays. Use web-first assertions (`await expect(locator).toHaveCount(n)`).
  • Network-stub fix introduces new bugs if the stub schema drifts from real responses: mention in 'Why this works' that schema parity must be maintained.
  • Model adds extra assertions while rewriting (scope creep): keep the same assertions, only change the wait strategy.

Tips

  • Paste the actual failure log if available: it often contains the smoking gun (e.g., timeout duration, last successful state).
  • Run the rewritten test 20 times locally before claiming it's stable; flake is statistical.
  • Pair with `review-test-code-anti-patterns` to find the same class of flake across the suite.
  • If the suite has many hard sleeps, batch-fix them via `sync-waits-to-auto-waiting` instead of one by one.

FAQ

When are retries acceptable?

When the root cause is genuinely outside your test: e.g., a third-party CDN with intermittent timeouts, or shared test infrastructure that occasionally hiccups. Retries are wrong when the cause is in YOUR code or YOUR test. The categorization above is for the second case.

How do I find flaky tests at scale?

Track flake rate over time: Playwright marks tests that pass on retry as "flaky" in its reports, and dashboards such as Currents, Allure history, Datadog CI Visibility or CircleCI's flaky-test detection aggregate it across runs. Sort by failure rate over the last 30 days; anything > 2% is flaky enough to investigate. Don't wait for someone to complain.

Can the same prompt fix multiple tests at once?

No: feed one test at a time. Batch fixing usually misclassifies causes because tests share files and the model averages signals across them.

What about flaky-by-design tests (deliberately probabilistic)?

Make them deterministic for CI (seed the random source) and run a separate non-deterministic suite outside the merge gate. Don't let probabilistic tests block PRs.