How to Debug Flaky Playwright Tests: Find the Root Cause and Fix It


A flaky Playwright test is a test that produces inconsistent results even though the application code and test steps have not intentionally changed.

For example, a login test may pass on Monday, fail on Tuesday, and pass again when you rerun it.

These failures waste time because developers cannot easily tell whether the application is broken or the test itself is unreliable.

The best way to debug flaky Playwright tests is to reproduce the failure, collect evidence, identify the condition that changes between runs, and fix the underlying cause.

This guide explains how to recognize flaky tests, investigate their causes, use Playwright's debugging tools, and prevent similar problems in future automation projects.

1. What Is a Flaky Playwright Test?

A flaky test is a test whose result changes between runs without an intentional change to the tested behavior.

A test that fails on its first attempt but passes on a retry may be classified as flaky by Playwright's test runner.

For example, imagine a test that checks whether an order confirmation message appears.

The test passes when the application responds quickly but fails when the response takes longer.

The inconsistent result suggests that the test may depend on timing or application state.

However, not every intermittent failure is a test defect. The application, network, browser, or backend service may also be unreliable.

The goal of debugging is to determine which part is responsible.

2. What Causes Playwright Tests to Become Flaky?

Several problems can produce inconsistent results.

Timing problems

A test performs an action before the application reaches the required state.

Unreliable locators

A locator matches the wrong element or becomes invalid when the page changes.

Shared test data

Two tests update the same account or database record.

Parallel execution

Tests interfere with each other when they run simultaneously.

Network instability

An API request fails, responds slowly, or returns unexpected data.

Environment differences

Tests behave differently across browsers, operating systems, and CI runners.

Animations and dynamic interfaces

A menu, dialog, or button changes position or visibility while the test is running.

Understanding these categories helps you choose the correct debugging method.

3. Step One: Reproduce the Flaky Test

Before changing the test code, try to reproduce the failure.

Start by running the affected test file:

npx playwright test tests/login.spec.js


Replace the filename with your actual test file.

Next, repeat the test without retries:

npx playwright test tests/login.spec.js --repeat-each=10 --retries=0


This runs the selected test repeatedly and disables retries.

If the test fails intermittently, you have evidence that the problem can be reproduced under the current conditions.

If it passes every time, the problem may depend on CI, parallel execution, test data, or another condition that is absent from your local environment.

Ten repetitions are only an initial experiment, not proof that a test is stable.

For difficult intermittent failures, increase the number of repetitions and preserve the logs.

4. Step Two: Read the Error Message Carefully

The error message often identifies the operation that failed.

For example:

TimeoutError: locator.click: Timeout exceeded


This indicates that the click operation did not complete within the allowed time.

It does not automatically mean that the timeout setting is too small.

Possible causes include:

  • The locator matches no element.

  • The element is covered by another element.

  • The element is disabled.

  • The application is still loading.

  • The page is displaying an unexpected state.

Inspect the full error and call log before deciding what to change.

A useful debugging habit is to ask three questions:

  1. What was Playwright trying to do?

  2. What condition prevented the operation from completing?

  3. What evidence can confirm the suspected cause?

These questions help prevent guesswork.

5. Step Three: Replace Fixed Waits with Meaningful Conditions

One common source of flaky tests is a fixed delay.

Consider this example:

await page.waitForTimeout(2000);


await page.getByRole('button', {

  name: 'Save'

}).click();


The test waits for two seconds, regardless of whether the application is ready.

If the page is ready after 300 milliseconds, the test wastes time.

If the page needs three seconds, the test may still fail.

A better approach is to interact with the intended element and verify the result.

const saveButton = page.getByRole('button', {

  name: 'Save'

});


await expect(saveButton).toBeVisible();

await expect(saveButton).toBeEnabled();


await saveButton.click();


await expect(

  page.getByText('Changes saved')

).toBeVisible();


This example checks the button's state and then verifies the expected outcome.

Use the real button name and confirmation text from your application.

Playwright's auto-waiting helps with supported actions, while web-first assertions repeatedly check the expected condition until it succeeds or times out.

If the confirmation never appears, inspect the application response instead of simply increasing the delay.

6. Step Four: Use Trace Viewer to Understand the Failure

A trace records useful information about a test run, including actions, page snapshots, and other debugging details.

Trace Viewer helps you examine what happened before a test failed.

For example, a test may report that a checkout button was not clickable.

The trace might show that a loading overlay was still covering the button.

Without the trace, you might incorrectly assume that the locator was broken.

How to configure tracing

You can configure Playwright to retain traces when tests fail:

import { defineConfig } from '@playwright/test';


export default defineConfig({

  use: {

    trace: 'retain-on-failure'

  }

});


This setting retains traces for failed tests rather than recording them for every successful run.

After a failed test produces a trace archive, open it with:

npx playwright show-trace path/to/trace.zip


Replace the example path with the actual trace file.

Inspect the steps around the failure, including the page snapshot, action details, and any available network information.

The trace should help you form a hypothesis that you can test, rather than encouraging you to change code without evidence.

For additional debugging techniques, see the official Playwright debugging guide.

7. Step Five: Check for Unstable Locators

A test can become flaky when its locator depends on a changing page structure.

For example:

await page.locator(

  'div.container > div:nth-child(3) > button'

).click();


This selector depends on the layout remaining unchanged.

If another element is inserted before the button, the selector may point to something else.

Where possible, use a locator based on the element's role and accessible name.

await page.getByRole('button', {

  name: 'Place order'

}).click();


This example is clearer because it describes the intended action.

However, role-based locators are not automatically unique. Confirm that the locator identifies the correct element.

If several buttons share the same name, scope the locator to the relevant section or improve the application's accessible labels.

The Playwright Locators guide explains how to build more reliable selectors.

8. Step Six: Investigate Shared Test Data

Some flaky tests are caused by shared backend data rather than browser interactions.

Imagine two tests that use the same customer account.

One test changes the customer's address while another checks the original address.

If the tests run simultaneously, their results may depend on which update happens first.

How to fix shared-data problems

  • Create separate test accounts when possible.

  • Generate unique test records.

  • Reset data before tests that require a known state.

  • Avoid relying on records created by unrelated tests.

  • Clean up test data when appropriate.

  • Check whether parallel workers modify the same backend resources.

Remember that Playwright browser contexts isolate browser sessions, but they do not automatically isolate external databases.

If two tests update the same backend record, separate browser contexts alone will not solve the problem.

9. Step Seven: Investigate Network and API Failures

A page can appear normal even when an important API request has failed.

For example, the dashboard heading may appear while the account information request returns an error.

A test that checks only the heading may pass even though the account data never loads.

Another test that checks the account information may fail.

Inspect the relevant network requests and application logs.

Confirm whether the request succeeded, whether the response contains the expected data, and whether the interface handled errors correctly.

If the application uses an API to prepare test data, make sure that the API call completes successfully before the test depends on its result.

Do not automatically treat every network delay as a Playwright problem. The underlying service may need investigation.

For API-related automation concepts, explore the Playwright API Testing guide.

10. Step Eight: Check Whether Parallel Execution Causes the Failure

If a test passes alone but fails when the full suite runs, investigate parallel execution.

Other tests may be consuming system resources or changing shared application data.

As a diagnostic step, configure a single worker in CI:

import { defineConfig } from '@playwright/test';


export default defineConfig({

  workers: process.env.CI ? 1 : undefined

});


Run the affected suite again.

If the failures disappear, investigate resource limits, test isolation, and shared state.

One worker can help identify the problem, but it should not become a substitute for correcting tests that interfere with each other.

Once the cause is fixed, evaluate whether parallel execution can be restored safely.

11. Step Nine: Use Retries as Diagnostic Evidence

Playwright supports retries for failed tests.

For example:

npx playwright test --retries=2


This allows a failing test to be attempted again according to the configured retry policy.

Retries are useful for identifying intermittent failures, especially in CI.

However, a test that passes after a retry has not necessarily become reliable.

The retry may simply have hidden a timing problem or an intermittent application defect.

Use the test report to identify flaky results, then investigate the original failure.

Do not measure test quality only by the number of tests that eventually pass.

Measure it by how consistently the tests produce trustworthy results.

12. A Simple Decision Tree for Flaky Test Debugging

Use this process to narrow down the problem.

If the test fails every time:

Check the locator, assertion, application behavior, configuration, and test data.

If the test fails only sometimes on your laptop:

Repeat it with retries disabled and inspect the trace for timing or state changes.

If the test fails only in CI:

Compare the browser version, operating system, environment variables, test data, and available resources.

If the test fails only when running the complete suite:

Investigate shared state, parallel execution, test ordering, and resource usage.

If the test fails on a specific browser:

Compare browser-specific behavior, configuration, rendering, and application compatibility.

This process helps you narrow down the likely cause before making changes.

Frequently Asked Questions

How do I identify a flaky Playwright test?

Run the test repeatedly with retries disabled and compare the results. If it fails intermittently, inspect the error messages, traces, environment, and test data to find the changing condition.

Does increasing the timeout fix flaky tests?

Not always. A longer timeout may help when an operation legitimately needs more time, but it will not correct an incorrect locator, shared data, or a failing API.

How can I debug flaky Playwright tests in CI?

Collect the failed test's trace and logs. Compare the CI environment with the successful local environment and investigate timing, browser dependencies, environment variables, and parallel execution.

Should every Playwright test use retries?

Retries are a configuration choice, not a replacement for reliable test design. They can help identify intermittent failures, but recurring flaky tests should still be investigated.

What is the most effective way to prevent flaky tests?

Use reliable locators, meaningful assertions, independent test data, consistent environments, and clear debugging evidence. Run tests repeatedly when necessary and investigate inconsistent results instead of ignoring them.

Conclusion

Flaky Playwright tests become easier to diagnose when you stop treating them as random failures.

Reproduce the problem, read the error message, inspect the trace, compare successful and failed runs, and identify the condition that changes.

Then correct the underlying issue and rerun the test to verify the result.

Reliable automation depends on tests that check real application behavior consistently—not tests that happen to pass after several attempts.

For more practical automation resources, visit PlaywrightMasters and explore its learning guides on debugging, locators, fixtures, API testing, and the Playwright roadmap.


Comments

Popular posts from this blog

How to Run Only Smoke Tests in Playwright: Step-by-Step Guide

How to Test REST APIs Using Playwright

Playwright Multiple Tabs and Windows Explained: A Practical Guide