Finding and fixing flaky tests

Prove a test is stable

A test that passed once proves little. Run it many times in a row. Flaky tests usually fail within 20 runs:

npx playwright test flaky-lab --repeat-each=20

1. Random delays

The report takes between 1 and 7 seconds. A fixed waitForTimeout(3000) fails most of the time. Plain toBeVisible() fails sometimes, because 7 seconds is longer than the default 5-second timeout. Give the check a timeout above the slowest realistic case:

await page.getByRole('button', { name: 'Fetch report' }).click();
await expect(page.getByTestId('report')).toBeVisible({ timeout: 10_000 });

2. Content that re-renders

The service list is rebuilt every second, in a new order. A locator is a description, not an element: it finds the element again each time you use it, so re-renders do not matter. An element handle points at one specific node, which can be thrown away a moment later.

// ✅ Finds "Beta" again at the moment of the click, wherever it moved.
await page
  .getByRole('listitem')
  .filter({ hasText: 'Beta' })
  .getByRole('button', { name: 'Select' })
  .click();

// ❌ Position-based: the list reshuffles, so nth(1) is a different service.
// await page.getByRole('button', { name: 'Select' }).nth(1).click();

3. Responses that arrive before you listen

The save request finishes in a few milliseconds. If you start waiting after the click, the response may already have arrived, and the wait hangs until it times out.

// ❌ Race: the response can arrive before waitForResponse starts.
await page.getByRole('button', { name: 'Quick save' }).click();
await page.waitForResponse('**/api/status/200');

// ✅ Start waiting first, then trigger it.
const responsePromise = page.waitForResponse('**/api/status/200');
await page.getByRole('button', { name: 'Quick save' }).click();
await responsePromise;

Retry a whole block: toPass()

When several steps must succeed together, wrap them in expect(async () => …).toPass(). The whole block retries until it passes or times out.

Test retries in the config can make a flaky test look green while hiding the problem. Fix the cause; use retries only as a safety net.

1. Random delay

The report takes between 1 and 7 seconds, different every time.

2. Re-rendering list

Rebuilt every second in a new order. Render #0

  • Alpha
  • Beta
  • Gamma
Selected service: none

3. Fast response

Sends a request that completes almost instantly.