Finding Flaky Tests: A Practical Guide
In this article
Flaky tests are tests that pass and fail without any code changes, eroding developer trust in the test suite and slowing down releases. This guide walks you through a systematic process to identify, diagnose, and fix flaky tests, restoring confidence in your CI pipeline. You'll learn to use both manual and automated strategies, from simple reruns to advanced tooling.
What You'll Need
- Access to your CI system (Jenkins, GitHub Actions, CircleCI, etc.) and its logs.
- A way to rerun failed tests (CI UI button or command-line tool).
- Basic familiarity with your test framework (e.g., JUnit, pytest, Jest).
- Optional: A test analytics tool like BuildPulse, Test Analytics by Datadog, or a custom script to track test history.
- Optional: A local development environment to reproduce and debug.
Step-by-Step
- Collect data on test failures. Start by gathering a list of tests that have failed in the last 2-4 weeks. Use your CI's API or a spreadsheet to log each failure: test name, date, commit hash, CI job ID, and the error message. Look for tests that fail on one run and pass on a rerun—these are your primary suspects.
- Calculate flake rate. For each suspect test, count how many times it failed vs. how many times it ran. A test that fails 1 in 100 runs is flaky, but a test that fails 1 in 10 is a major problem. Prioritize tests with a flake rate above 1% (or any test that has failed more than twice in the period).
- Rerun to confirm. Use your CI's "rerun failed tests" feature to see if the test passes on retry. If it does, it's definitely flaky. If it fails consistently, it's a regular failure, not a flake—move on.
- Isolate the test. Run the flaky test in isolation locally. If it passes consistently, the flake is likely due to test interference or shared state. If it fails intermittently even in isolation, the issue is likely timing-related or environmental.
- Check for order dependence. Run the test suite in random order (many frameworks support this, e.g., pytest-randomly, JUnit's random order). If the test fails more often in a particular order, it's order-dependent. Try to find which test leaves behind state that causes the failure.
- Look for timing issues. Examine the test code for hard-coded waits (e.g.,
sleep(5)) or asynchronous operations that aren't properly awaited. Replace fixed sleeps with explicit waits for conditions (e.g., WebDriverWait,awaitwith timeouts). - Check for resource leaks. Tests that create files, database connections, or network sockets without cleanup can cause flakiness. Look for tests that don't use
try/finallyor@Aftermethods to release resources. - Examine shared static state. Static variables, environment variables, or system properties that change during a test can affect others. Use a tool like
junit-quickcheckor manually reset static state in@Beforemethods. - Use a test analytics tool. If manual tracking is too tedious, integrate a tool that automatically tracks test history and flags flaky tests. These tools often provide a heatmap of flakiness and can be integrated into CI to quarantine flaky tests.
- Fix the root cause. Once you've identified the cause, fix it. Common fixes include: adding proper synchronization, cleaning up test data, using unique test data per run, or increasing timeouts. After fixing, rerun the test many times (e.g., 50 times) to confirm it's stable.
- Quarantine if needed. If a test is too complex to fix immediately, move it to a separate "flaky" suite that doesn't block the main pipeline. This keeps the main suite green while you work on the fix. But don't leave it there forever—set a deadline to fix it.
Common Mistakes
- Ignoring flaky tests. The worst mistake is to just rerun and move on. This erodes trust and hides real bugs.
- Fixing symptoms, not causes. Increasing timeouts to 30 seconds might make a test pass, but it slows down the suite and masks the real issue.
- Not cleaning up test data. Tests that rely on specific database states or files that aren't cleaned up will fail when run after other tests.
- Using
sleep()instead of explicit waits. Sleeps are brittle and often too short or too long. - Assuming it's the test's fault. Sometimes the application code has a race condition. Don't only look at the test code.
Tips
- Start with the most recent failures. They're more likely to be related to recent code changes.
- Keep a log of flaky tests. A simple spreadsheet or GitHub issue template helps track progress.
- Automate detection. Add a CI step that runs the test suite multiple times (e.g., 3x) and fails if any test fails only once—this catches flakes early.
- Use test sharding carefully. Sharding can introduce new order-dependent flakes. If you shard, ensure each shard is independent.
- Write tests that are deterministic. Avoid using random data without seeding, and always mock external services.
Troubleshooting
- Test fails only on CI, not locally. This is often due to different timing, file paths, or environment variables. Use the CI's logs to compare the environment. Try running the test in a Docker container that mimics CI.
- Test fails intermittently even in isolation. This could be a real race condition in the application code. Use a debugger or add logging to see where it hangs. Also check for flaky network calls or date/time dependencies.
- Rerunning doesn't help. If a test fails every time, it's not a flake—it's a broken test. Follow normal debugging steps.
- You can't reproduce the failure. Try running the test in a loop (e.g.,
for i in {1..50}; do pytest test; done) to increase the chance of reproduction. Also, capture more logs from CI.
Frequently Asked Questions
What exactly counts as a flaky test?
A test that produces different results (pass/fail) under the same code and environment, without any intentional changes. It's a false alarm that wastes time.
How many reruns should I allow before giving up?
One or two reruns are common to confirm a flake. If it fails more than that, treat it as a real failure. Automating this with a max retry count is best.
Can flaky tests be caused by the CI infrastructure?
Yes. Slow machines, network timeouts, or resource contention can cause flakes. If you suspect this, run the test on a different CI runner or locally to compare.
Should I delete a flaky test that I can't fix?
Deleting a test removes coverage, so it's a last resort. Quarantine it first, then try to fix it. If you truly can't fix it, delete it and write a better test.
What's the best way to prevent flakes in new tests?
Write tests that are isolated (no shared state), use explicit waits, and mock external dependencies. Also, run new tests multiple times in CI before merging.
How do I convince my team to spend time on flaky tests?
Show the cost: time spent rerunning, lost productivity, and missed bugs. Propose a dedicated "flaky test day" or a budget of 10% of sprint time to fix them.