---
title: "How to fix flaky browser tests in Playwright and Selenium"
description: "Fix flaky browser tests by first proving they are flaky (run them many times), then separating environment trouble from test bugs, then removing the cause, usually timing, shared state or overloaded machines. Retries and traces find flaky tests; auto-waiting, isolation and fewer workers fix them."
url: "https://www.agentsandbox.host/p/fix-flaky-browser-tests/"
site: "AgentSandbox.host"
author: "AgentSandbox.host editors"
published: "2026-11-26"
updated: "2026-11-26"
---

# How to fix flaky browser tests in Playwright and Selenium

AgentSandbox.host editors. Published 2026-11-26, updated 2026-11-26.

Fix flaky browser tests by first proving they are flaky (run them many times), then separating environment trouble from test bugs, then removing the cause, usually timing, shared state or overloaded machines. Retries and traces find flaky tests; auto-waiting, isolation and fewer workers fix them.

A flaky browser test is one that passes and fails on the same code. Playwright Test gives the category its own name: "flaky: tests that failed on the first run, but passed when retried" ([Playwright retries](https://playwright.dev/docs/test-retries), read 2026-11-26). Fixing flakiness is a four-step job: prove it, find whose fault it is, read what happened, and remove the cause.

## Step 1: How do I prove a test is flaky?

Prove a test is flaky by running it many times on unchanged code. Playwright Test has a flag for it: `--repeat-each <N>`, "Run each test `N` times" ([Playwright command line](https://playwright.dev/docs/test-cli), read 2026-11-26).

```
npx playwright test tests/checkout.spec.ts --repeat-each=20 --workers=4
```

1. Use the same worker count as the machine where it flakes; load is part of the cause.
2. Add `--shuffle` to change the order; a test that only fails after another test is a shared-state bug.
3. In CI, `--fail-on-flaky-tests` makes the run fail "if any test is flagged as flaky", so flaky passes stop counting as green.

## Step 2: Is it the test or the environment?

Decide this before touching the test: a crashed browser, a full disk or a registry that timed out make a correct test fail, and rewriting the test will not help. There are three ways to keep the two kinds of failure apart:

1. **Promigence's validity report.** Promigence returns a report after every run that classifies each sandbox's outcome (Promigence FAQ, read 2026-11-26). Its quickstart lists what the report holds: completed runs, task failures, environment failures and the cost, where a task failure means "your command exited non-zero" and an environment failure "never counts against your agent" (the quickstart, read 2026-11-26). Its errors page gives each kind its own exit code, 3 for "Environment failure: the environment failed, not your command" and 4 for "Task failure: your command failed", and says an environment failure is "kept out of your result and retried once before hand-over" (the errors page, read 2026-11-26). To rerun one result by hand, `promigence run report <run_id> --sandbox <sid> --repro` prints the command that reproduces it, and its replay command, `promigence run replay`, runs the environment's share of a run again as new sandboxes billed under the run's cap (Promigence FAQ). The security page adds that "A failed sandbox's state is kept for up to 7 days by default", so the sandbox where a test went wrong can be reopened and looked at (the security page, read 2026-11-26). The command for that is `promigence run open`.
2. **Playwright's own signals.** When a test fails, "Playwright Test will discard the entire worker process along with the browser and will start a new one" (Playwright retries, read 2026-11-26). A browser that never launched points at the environment; `DEBUG=pw:browser` logs the launch, which Playwright calls "helpful while debugging Error: Failed to launch browser errors" ([Playwright CI](https://playwright.dev/docs/ci), read 2026-11-26).
3. **Your own bookkeeping.** Record the machine, container id and exit reason with every result, and compare failure rates per machine. A test that fails on one host and nowhere else is an environment problem.

Other hosted services expose the environment side through their own errors and states, which you can log beside each test result (read 2026-11-26):

- **AWS:** Amazon Bedrock AgentCore Runtime stops a session whose compute "is deemed unhealthy based on health checks", and a call that arrives while a session is being set up or torn down gets a retryable HTTP 409 (AgentCore sessions documentation).
- **Daytona:** a command that fails returns its non-zero `exitCode` in the response, problems on the sandbox's side are raised as a `DaytonaError` (Daytona process documentation), and a sandbox in the Error state "needs to be recovered" (Daytona sandboxes documentation).
- **E2B:** the SDK raises `SandboxNotRunningError` when a sandbox "is not running anymore", `SandboxUnreachableError` when it cannot be reached, and `ServiceBusyError` for an HTTP 503 after which nothing has changed and the call can be retried (E2B SDK error reference).
- **Google Cloud:** a Cloud Run job retries a failed task 3 times by default (Cloud Run maximum retries documentation), so check how many attempts a task needed before you call a test flaky.
- **Modal:** exit codes "are provided to help diagnose conditions such as success, manual termination, or out-of-memory", and a terminated Sandbox reports 137 (Modal Sandboxes guide).

## Step 3: How do I see what happened in a flaky run?

See what happened by recording a trace on the first retry and opening it. Playwright's configuration:

```ts
// playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  retries: process.env.CI ? 2 : 0,
  use: { trace: 'on-first-retry' },
});
```

The trace lets you "Inspect the log, source and network, errors, and console during each step of the test" ([Playwright trace viewer](https://playwright.dev/docs/trace-viewer-intro), read 2026-11-26); open it from the HTML report with `npx playwright show-report`, or directly with `npx playwright show-trace` and the file's path. Playwright advises against tracing every test: "We don't recommend setting this to `on` so that traces are run on every test as it's very performance heavy" ([Playwright best practices](https://playwright.dev/docs/best-practices), read 2026-11-26). In Python, `pytest --tracing retain-on-failure` keeps traces only for failed tests.

## Step 4: How do I remove the usual causes?

Remove the usual causes in this order: timing, shared state, load, then outside dependencies.

Table: Common causes of flaky browser tests and their fixes

| Cause | Symptom | Fix |
|---|---|---|
| Manual waits and instant checks | Fails on a slow run, passes on a fast one | Web-first assertions: `await expect(locator).toBeVisible()`, never `expect(await locator.isVisible()).toBe(true)` |
| Fixed sleeps | Fails under load | Remove `waitForTimeout`; wait for a state with `expect` or `expect.poll` |
| Shared state between tests | Fails only after a certain other test | A new context per test, and per-worker test data using `TEST_PARALLEL_INDEX` |
| Too many browsers per machine | Timeouts that grow with `--workers` | Fewer workers, or shard across machines |
| Third-party services | Fails when an outside site is slow or changes | Mock it with `page.route` and fulfil the response |
| Brittle selectors | Fails after markup changes | `getByRole` and other user-facing locators |

The sources for each fix:

- **Waiting.** Web-first assertions "will wait until the expected condition is met", while with `isVisible()` "the test won't wait a single second" (Playwright best practices, read 2026-11-26). The default assertion timeout is 5 seconds, and "using non-retrying assertions can lead to a flaky test" ([Playwright assertions](https://playwright.dev/docs/test-assertions), read 2026-11-26).
- **Isolation.** "Each test should be completely isolated from another test and should run independently" (Playwright best practices, read 2026-11-26).
- **Outside services.** "Only test what you control", using "the Playwright Network API" to "guarantee the response needed" (Playwright best practices, read 2026-11-26).
- **Missing awaits.** Playwright recommends the `@typescript-eslint/no-floating-promises` rule "to make sure there are no missing awaits".

## How do I fix flaky waits in Selenium?

Fix them with explicit waits for a condition. Selenium's docs explain the cause: "The processes often end up in a race condition where sometimes the browser gets into the right state first", and a sleep "can fail when it doesn't sleep long enough" ([Selenium waits](https://www.selenium.dev/documentation/webdriver/waits/), read 2026-11-26). The implicit wait defaults to 0, and the docs warn: "Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times." The docs' explicit wait in Python:

```python
from selenium.webdriver.support.wait import WebDriverWait

wait = WebDriverWait(driver, timeout=2)
wait.until(lambda _ : revealed.is_displayed())
```

## When are retries the right answer?

Retries are the right answer for failures you have proved come from the environment, not from the test. Playwright's retries are off by default; `retries: 2` or `--retries=2` turns them on, and a retried pass is reported as flaky rather than passed (Playwright retries, read 2026-11-26). Keep that report visible, and treat every test that appears in it as a bug to fix with the table above.

## What we read for this article

- Promigence quickstart, [https://www.promigence.ai/docs/quickstart](https://www.promigence.ai/docs/quickstart), read 2026-11-26
- Promigence FAQ, [https://www.promigence.ai/faq](https://www.promigence.ai/faq), read 2026-11-26
- Promigence errors page, [https://www.promigence.ai/docs/errors](https://www.promigence.ai/docs/errors), read 2026-11-26
- Promigence security page, [https://www.promigence.ai/security](https://www.promigence.ai/security), read 2026-11-26
- [Amazon Bedrock AgentCore sessions documentation](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-sessions.html), read 2026-11-26
- [Daytona process documentation](https://www.daytona.io/docs/en/process-code-execution) and [Daytona sandboxes documentation](https://www.daytona.io/docs/en/sandboxes), read 2026-11-26
- [E2B SDK error reference](https://docs.e2b.dev/sdk-reference/js-sdk/v2.64.0/errors), read 2026-11-26
- [Cloud Run maximum retries documentation](https://docs.cloud.google.com/run/docs/configuring/max-retries), read 2026-11-26
- [Modal Sandboxes guide](https://modal.com/docs/guide/sandbox), read 2026-11-26
- [Playwright retries](https://playwright.dev/docs/test-retries), read 2026-11-26
- [Playwright command line](https://playwright.dev/docs/test-cli), read 2026-11-26
- [Playwright CI](https://playwright.dev/docs/ci), read 2026-11-26
- [Playwright trace viewer](https://playwright.dev/docs/trace-viewer-intro), read 2026-11-26
- [Playwright best practices](https://playwright.dev/docs/best-practices), read 2026-11-26
- [Playwright assertions](https://playwright.dev/docs/test-assertions), read 2026-11-26
- [Selenium waits](https://www.selenium.dev/documentation/webdriver/waits/), read 2026-11-26

## FAQ

### What is a flaky test?

A flaky test passes and fails on the same code. Playwright Test labels a test flaky when it failed on the first run but passed when retried.

### Should I just turn on retries?

Retries keep a pipeline moving, but they hide the cause. Turn them on with tracing on the first retry, read the traces, and fix the tests that keep showing up as flaky. --fail-on-flaky-tests stops flaky passes from counting as green.

### How do I reproduce a flaky Playwright test locally?

Run it many times in a row with npx playwright test --repeat-each=20, optionally with --workers set to match the CI machine, and record a trace with --trace on.

### Why are my browser tests flaky only on CI?

CI machines often have fewer cores, so the same number of parallel browsers renders pages later than on a laptop and timing assumptions break. Lower the workers, or check whether the failures come from the environment rather than the tests.

### How do I avoid flaky waits in Selenium?

Replace sleeps with explicit waits for a specific condition, keep the implicit wait at its default of 0, and never mix implicit and explicit waits.
