REMEDIATION · 9 MIN READ

How to Fix Flaky Tests: Root Causes, Code Patterns, and Prevention

Actionable engineering playbook on how to fix flaky tests across timing races, shared state, network calls, concurrency, and test order.

1. Eliminate Timing and Race Conditions

Hard-coded sleep statements (sleep(500), setTimeout) are the single largest source of flaky tests. Under heavy CI load, a 500ms wait finishes before an async request or DOM transition completes. Replace arbitrary delays with deterministic condition polling, fake timers, or event-driven assertions.

// Bad: race-prone sleep
await new Promise((r) => setTimeout(r, 300));
expect(statusText).toBe('Saved');

// Good: deterministic wait / fake timers
await expect.poll(() => getStatusText(), { timeout: 5000 }).toBe('Saved');

2. Isolate Shared State and Parallel Workers

Tests that bind fixed ports (like 3000 or 8080), write to a shared temp path, or insert hardcoded emails into a shared PostgreSQL database will randomly collide when test runners execute files in parallel. Always bind port 0 for ephemeral test servers, use unique UUIDs or rolled-back transactions per test, and create isolated temporary directories.

3. Stub External Networks Deterministically

Unit and integration tests must never depend on live external APIs. Use Mock Service Worker (MSW), Nock, WireMock, or local test containers so network latency, rate limits, and third-party outages cannot poison your CI signal.

4. Quarantine While You Fix (Without Blocking Deploys)

When a critical release is blocked by a known flaky test, teams face an ugly choice: disable the entire test suite or repeatedly rerun CI. Automated quarantine solves this cleanly. FlakeCheck moves high-score flakes into non-blocking quarantine mode, tracks the owner and reason in an audit log, opens a Jira/Linear/GitHub issue, and automatically graduates the test back to blocking CI once it passes 10 consecutive runs.

Eliminate flaky tests automatically with FlakeCheck

Stream your JUnit, CTRF, Jest, Vitest, Playwright, Pytest, Mocha, or Go reports to FlakeCheck and get statistical scoring + auto-quarantine in minutes.

Related Guides