Full answer
A flaky test is one that gives different results for the same code. It is costly because the team learns to ignore red builds. Retries hide it, they do not fix it.
Find the cause first. Collect evidence from the failed run: a trace, a video, a screenshot, the console and network log. Browser test tools can record a trace on the first retry. Then look for the usual causes.
- Timing. The test acts or asserts before the page is ready:
sleep(500)is a guess that is right on a fast laptop and wrong on a slow runner. Fix: wait for a condition. Modern tools wait for elements to be visible, stable and enabled before an action, and web-first assertions retry until the expected state or a timeout. - Shared state. Tests depend on order, on data left by another test, or on the same user account while running in parallel. Fix: create the data each test needs through the API, use unique names, and run each test in a fresh browser context.
- Uncontrolled external inputs. Real third-party services, the current date, random values, animations. Fix: mock or stub them, fix the clock, disable animation in the test build.
- Brittle selectors. CSS paths and indexes break when the layout changes. Fix: use roles, labels and stable test ids.
- Environment. CI has fewer CPUs, a different viewport, fonts and time zone. Fix: pin versions with a container image, set viewport and locale in the config, and reproduce with the same container locally.
- Real bugs. Some "flaky" tests are correct and reveal a race in the app, such as a request that races a navigation. Do not dismiss them.
Process: measure the failure rate by running the test many times, quarantine a flaky test with a ticket and an owner, and delete tests that nobody trusts.
The script uses Playwright against a page that shows a result after 300 milliseconds. A fixed 50 millisecond sleep reads an empty result. The auto-waiting call waits until the text appears. The results of a real CI environment were not reproduced.
import { chromium } from 'playwright-core';
const browser = await chromium.launch({
executablePath: process.env.CHROME_PATH ?? '/usr/bin/google-chrome',
args: ['--no-sandbox'],
});
const page = await browser.newPage();
await page.setContent(`<button id="go">Load</button><p id="result"></p>
<script>go.onclick = () => setTimeout(() => { result.textContent = 'Loaded'; }, 300);</script>`);
await page.click('#go');
await page.waitForTimeout(50); // fragile: guesses the delay
console.log('fixed sleep saw:', JSON.stringify(await page.textContent('#result')));
await page.getByText('Loaded').waitFor(); // waits for the condition
console.log('auto-wait saw:', JSON.stringify(await page.textContent('#result')));
await browser.close();Run with Node 24.22.1. The output matched the text in the answer in two runs. Run with Node 24 and playwright-core with Chrome 156, using a local system Chrome. The output was identical in two runs. A CI environment, a trace viewer and parallel workers were not used. The path of the browser is set by CHROME_PATH.
Key points
- Find the cause with traces and logs before changing anything.
- Replace fixed sleeps with auto-waiting and web-first assertions.
- Isolate state and data for each test, and run each in a fresh context.
- Control time, network, randomness and animations.
- Retries hide flakiness. Quarantine, own and fix.
Common mistakes
- Adding retries or longer sleeps as the fix.
- Writing selectors from the DOM structure.
- Sharing one user account between parallel tests.
- Ignoring a flaky test that points to a real race in the app.
Follow-ups
- How do you measure the flake rate of one test?
- What does auto-waiting check before a click?
- When is a test not worth keeping?
Tips
- Group causes into timing, state, external inputs, selectors and environment.
- Say that evidence comes first and retries are not a fix.