Next-Gen App & Browser
Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud
  • Automation
  • Home
  • /
  • Learning Hub
  • /
  • How to Use Auto Heal in Playwright for Self-Healing Tests

How to Use Auto Heal in Playwright for Self-Healing Tests

Learn how auto heal in Playwright detects broken selectors, fix tests automatically, and helps maintain stable, reliable, self healing automation pipelines.

Published on: October 12, 2025

  • Share:

When you run Playwright tests, changes to element attributes, DOM structure, or selectors can cause tests to fail. However, implementing auto heal in Playwright testing can automatically identify broken locators and update them at runtime. This allows tests to continue executing without interruption, reducing false negatives, minimizing test maintenance, and ensuring that your test suite accurately reflects the functionality of your web application, even if its UI changes.

Overview

Auto heal in Playwright helps maintain test stability by detecting when elements change and updating failing locators automatically. This reduces manual fixes and ensures tests continue to run reliably even when page structures evolve.

How Auto Heal Works in Playwright?

Playwright’s auto heal feature intelligently identifies broken locators, finds valid alternatives, and updates them dynamically, keeping tests functional despite minor UI changes.

  • Smart Locator Queries: Playwright provides semantic locators like getByRole, getByText, and attribute-based selectors. These locators reflect user interactions and remain reliable as the UI changes.
  • Retry Logic and Adaptive Behavior: Actions are automatically retried when elements are temporarily unavailable, handling dynamic content and preventing unnecessary failures from short-lived changes.
  • Chaining and Scoped Queries: Locators can be chained and scoped to specific containers, making tests less dependent on the overall page structure and more resilient to DOM updates.
  • Reliable Compared to Traditional Tools: Unlike traditional tools that fail when selectors break, Playwright’s combination of stable locators, retries, and scoped queries helps tests continue running smoothly.

How to Use Auto Heal in Playwright?

Cloud testing platforms like LambdaTest offers an auto heal feature for Playwright, which automatically detects and updates failing locators during test execution, helping maintain stable tests across different browsers and operating systems.

  • Configure Browsers and OS on LambdaTest: In the capabilities object, specify browserName, browserVersion, and platform to run tests across desired environments.
  • Enable Auto Heal: Add autoHeal: true within the LambdaTest capabilities to allow automatic detection and correction of failing locators.
  • Set Up LambdaTest Credentials: Include your Username and Access Key in the capabilities to authenticate and execute tests on the LambdaTest cloud grid.
  • Run Tests on the LambdaTest Grid: Execute your Playwright scripts remotely; failing locators are automatically adjusted by auto heal feature to prevent test breaks.
  • Check Auto Heal Test Reports: Review LambdaTest logs to see which locators were updated and verify test reliability for ongoing maintenance.

What Is Auto Heal in Playwright?

Auto heal in Playwright testing refers to techniques that allow automated tests to recover from locator failures caused by UI changes. When a test script cannot find an element using its original selector, auto healing strategies attempt alternative ways to locate the element, such as using role-based locators, dynamic selectors, or retry logic.

Playwright does not include a fully built-in auto healing engine. However, you can use features like role-based Playwright locators, retry mechanisms, and dynamic selectors, which help create more reliable and maintainable tests.

How Auto Healing in Playwright Works?

Playwright enables resilient testing by combining strategies that make test execution more robust than traditional approaches. While it does not include a fully automatic auto healing engine, its features allow tests to adapt to minor UI changes and reduce ongoing maintenance.

  • Smart Locator Queries: Playwright provides semantic locators such as getByRole, getByText, and custom attribute-based selectors. These locators are more stable than static IDs or fragile XPath paths and reflect actual user interactions, helping tests remain reliable as the interface evolves.
  • Retry Logic and Adaptive Behavior: When an element is temporarily unavailable, Playwright automatically retries actions for a configurable timeout. This approach handles dynamic content, waits for element stabilization, and reduces false failures caused by transient UI changes. Playwright timeouts define how long these retries continue, ensuring tests wait appropriately before failing due to temporary unavailability.
  • Chaining Locators and Scoping Queries: You can chain locators and scope queries to specific containers. This makes tests less dependent on the global page structure and more resilient to small DOM changes.
  • Contrast With Traditional Tools: Traditional tools often fail immediately when a selector breaks, requiring manual intervention. Playwright’s combination of stable locators, retries, and scoped queries reduces maintenance and helps teams maintain reliable test suites.
Note

Note: Run Playwright tests with auto healing across over 3000 real environments. Try LambdaTest Now!

How to Use Auto Heal in Playwright?

Let’s look at Playwright auto heal mechanism to enhance test resilience, leveraging smart locators that adapt to UI changes automatically during execution.

Setting Up the Environment

Install Playwright using the command below:

npm init playwright@latest

After Playwright installation, you’ll have a fully configured project with:

  • A playwright.config.js file.
  • A tests/ folder with sample test files (that you can delete).
  • A tests-examples/ folder with some sample test files (that you can also delete).
  • All required dependencies and browser binaries are installed.

Writing the Tests

Let’s test a user registration flow on the LambdaTest eCommerce Playground website.

Test Scenario:

  • Open the LambdaTest eCommerce Playground registration page.
  • Enter user details with a unique generated email.
  • Set and ensure a secure account password.
  • Select newsletter subscription and accept site terms.
  • Submit the form and verify account creation success.

Implementation:

Here is the register.spec.js file optimized with resilience in mind:

import { test, expect } from '@playwright/test';

function generateEmail() {
  const timestamp = Date.now();
  return `user${timestamp}@mail.com`;
}

test('Create new user account with resilient locators', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/register');

  await page.getByLabel('First Name').fill('Maria');
  await page.getByLabel('Last Name').fill('Costa');
  await page.getByLabel('E-Mail').fill(generateEmail());
  await page.getByLabel('Telephone').fill('+351123456789');
  await page.getByLabel('Password', { exact: true }).fill('987654321');
  await page.getByLabel('Password Confirm', { exact: true }).fill('987654321');

  await page.getByText('Yes').click(); // Newsletter opt-in
  await page.getByText('I have read and agree').click(); // Privacy Policy

  await page.getByRole('button', { name: 'Continue' }).click();

  await expect(page).toHaveTitle('Your Account Has Been Created!');
});

test('Create new user account with strategies for handling dynamic components', async ({ page }) => {
  await page.goto('https://ecommerce-playground.lambdatest.io/index.php?route=account/register');

  await expect(page.getByRole('heading', { level: 1 })).toHaveText('Register Account');

  await page.getByLabel('First Name').fill('Maria');
  await page.getByLabel('Last Name').fill('Costa');
  await page.getByLabel('E-Mail').fill(generateEmail());
  await page.getByLabel('Telephone').fill('+351123456789');
  await page.getByLabel('Password', { exact: true }).waitFor({ state: 'visible' });
  await page.getByLabel('Password', { exact: true }).fill('987654321');

  await page.getByLabel('Password Confirm', { exact: true }).fill('987654321');

  await page.getByText('Yes').click(); // Newsletter opt-in
  await page.getByText('I have read and agree').click(); // Privacy Policy

  await page.getByRole('button', { name: 'Continue' }).click();
  await page.waitForURL(/.*account/success/);

  await expect(page).toHaveTitle('Your Account Has Been Created!');
});

LambdaTest Playwright Auto Heal GitHub Repository

Why Is This Implementation “Auto Healing Ready”:

Let’s break down why the above test script is more resilient than one using static selectors:

  • Semantic Locators: Instead of By.ID or hardcoded XPath, we use getByLabel, getByText and getByRole, which are more stable and less affected by layout or ID changes.
  • Retry Logic Built-In: Playwright automatically retries actions like .click() or .fill() until the element is ready. You don’t need to manually wrap interactions in loops or waits.
  • Dynamic Data: We use a function to generate a unique email for every run, preventing failures from duplicate account creation.

Code Walkthrough:

  • Imports and Setup: Loads Playwright test and expect, providing testing framework and assertion tools to run and validate browser interactions.
  • Dynamic Email Generation: Uses a timestamp to create unique email addresses each run, preventing duplicate account errors during repeated test executions.
  • Form Interaction: Navigates to the registration page and fills the first name, last name, email, telephone, and password fields using stable semantic locators.
  • Options and Submission: Clicks newsletter subscription, privacy policy, and submits form via role-based Continue button, ensuring resilience against UI changes.
  • Validation: Ensures account creation by asserting page title, verifying the workflow completed successfully, and handling potential minor DOM or UI changes.

Test Execution:

To run the above spec file, execute the following command:

npx playwright test tests/register.spec.js
LambdaTest eCommerce Test Execution

How Does LambdaTest Playwright autoHeal Capability Help?

Cloud testing platforms such as LambdaTest offer a Playwright automation cloud to run your tests at scale across different browsers and operating systems. This platform offers a Playwright autoHeal capability that stores metadata from successful runs and finds alternative selectors when failures occur.

When a test in the future runs into a missing selector, this autoHeal capability compares the current web page with the saved reference data. It then automatically looks for a matching element, and if one is found, the test keeps running without any interruption.

To get started, check out this guide to use Playwright auto healing on LambdaTest.

Enabling the autoHeal Capability

We will run the same test scenario using the autoHeal capability provided by LambdaTest.

To activate the Playwright autoHeal capability, all you need to do is configure a new project entry inside your playwright.config.js file. There’s no need to change your test logic or add any dependencies, as the setup happens entirely through the configuration.

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

const LT_USERNAME = process.env.LT_USERNAME;
const LT_ACCESS_KEY = process.env.LT_ACCESS_KEY;

const ltCapabilities = {
  browserName: 'Chrome',
  browserVersion: 'latest',
  'LT:Options': {
    platform: 'Windows 10',
    build: 'Playwright Auto Heal Build',
    name: 'Playwright Auto Heal Test',
    autoHeal: true,
    user: LT_USERNAME,
    accessKey: LT_ACCESS_KEY,
  },
};

const ltWsEndpoint = `wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(ltCapabilities))}`;

export default defineConfig({
  testDir: './tests',
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 1 : undefined,
  reporter: 'html',
  use: {
    trace: 'on-first-retry',
  },
  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },
    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
    },
    {
      name: 'webkit',
      use: { ...devices['Desktop Safari'] },
    },
    {
      name: 'LambdaTest-Chrome-AutoHeal',
      use: {
        connectOptions: {
          wsEndpoint: ltWsEndpoint,
        },
      },
    },
  ],
});

Code Walkthrough:

  • Imports and Credentials: Imports Playwright’s defineConfig and devices. Retrieves LTUSERNAME and LTACCESS_KEY from environment variables for secure LambdaTest authentication.
  • LambdaTest Capabilities Setup: Defines ltCapabilities with browser, OS, and metadata like build and test names, controlling execution behavior in the cloud.
  • Auto-Heal Activation: Enables autoHeal: true inside LT:Options to automatically recover from broken locators during runtime without manual fixes.
  • WebSocket Endpoint Configuration: Builds ltWsEndpoint using LambdaTest’s CDP endpoint, embedding encoded capabilities to create a remote WebSocket connection for Playwright sessions.
  • Global Playwright Configuration: Configures test directory, parallelization, retries, tracing, and HTML reporting to ensure stable execution and detailed debugging information.
  • Project Definitions: Declares projects for Chromium, Firefox, WebKit, and LambdaTest-Chrome-AutoHeal, connecting cloud execution through the configured WebSocket endpoint.

Test Execution:

To run your tests using the Playwright autoHeal capability, simply execute the command below:

npx playwright test --project=LambdaTest-Chrome-AutoHeal
LambdaTest eCommerce Test Execution

Pro-tip: You can also leverage Generative AI testing agents like LambdaTest KaneAI that enhance automation reliability with its GenAI-native auto heal feature.

Instead of failing immediately when locators break, the auto heal feature dynamically identifies alternative locators at runtime, leveraging the natural language prompts used to generate the test.

To get started, check out this documentation on using auto healing in LambdaTest KaneAI.

...

Limitations and Considerations With Auto Heal

Playwright auto healing capabilities bring flexibility to UI automation, but it is essential to understand where they work and where they have limitations.

  • Produce False Positives: A key challenge with auto healing is false positives. If a button is removed or its behavior changes, Playwright may target a nearby or similarly labeled element.
  • This can let tests pass while the actual user experience is broken. The risk is higher when relying on text- or role-based selectors, as healed interactions may hit visually similar but functionally different elements, giving the test suite a misleading sense of reliability.

  • Affects Reliability and Performance: Playwright’s retry logic and flexible locators are effective for dynamic applications, but they have limits. Auto heal handles small changes like attribute updates reliably, but it struggles when the DOM structure changes significantly or interactive elements are replaced.

    Frequent healing attempts also increase execution time, especially in large test suites or pipelines, since retries and alternative locator resolutions add overhead that compounds at scale.

Best Practices for Using Auto Healing in Playwright

Auto‑healing can save significant effort in maintaining test suites in applications where the UI frequently changes. To benefit fully without introducing hidden risks, it must be used consciously.

Here are some best practices to balance robustness and correctness when enabling and relying on Playwright’s auto‑heal capabilities:

  • Treat Healing as a Backup, Not the Primary Mechanism: Let auto healing act as a protection layer rather than the main strategy. Fragile locators that repeatedly trigger healing should be refactored with stable attributes like data-test, data-id, or more reliable label- and role-based selectors.
  • Track and Review Every Healing Incident: Record each occurrence of auto healing. Even without built-in logs, you can wrap calls or add custom tracking to distinguish between legitimate recovery and underlying defects.
  • Pair Healing With Strong Validations: Locating an element is only half the test. Always validate outcomes after healed actions by asserting navigation, messages, or UI states to confirm correct functionality.
  • Limit Auto Healing on Critical Workflows: For login, checkout, or sensitive data submission, rely on strict locators and fail-fast behavior. Use auto heal primarily for maintenance flows, optional features, or non-critical UI elements.
  • Use Healing Events to Improve Test Design: Treat healed events as feedback. Review why locators failed, strengthen selectors, adjust UI markup if needed, and gradually reduce reliance on auto healing for long-term test stability.

Conclusion

Auto healing in Playwright helps maintain reliable tests despite frequent UI changes by automatically recovering from minor DOM or attribute modifications. It works through resilient locator strategies, automatic retries, and adaptive behavior, reducing the need for constant manual intervention.

Platforms like LambdaTest enhance this capability by dynamically finding alternative locators during cloud execution. While auto healing improves test stability, it is not a substitute for good test design, making monitoring and validations essential. Combining auto healing with strategies for handling dynamic components and enforcing strong assertions allows you to build robust, maintainable, and adaptive test suites.

Citations

Frequently Asked Questions (FAQs)

How does Playwright auto heal work?
Playwright auto heal tracks locator failures, compares them with known element patterns, and tries fallback selectors. It can use text content, attributes, or positional strategies to find elements, allowing tests to continue without manual intervention while keeping test results reliable.
Does auto heal affect test speed in Playwright?
Auto heal introduces slight overhead because Playwright must evaluate alternative selectors when failures occur. However, in practice, this cost is minimal compared with the time saved from avoiding broken tests and manual fixes, especially in large test suites with dynamic content.
Can I customize auto heal in Playwright?
Yes, Playwright allows configuring auto heal strategies by prioritizing locator types, defining fallback rules, or disabling auto heal for critical steps. Customization ensures that only suitable elements are auto healed, preventing false positives and maintaining test accuracy in complex applications.
What are common mistakes when using Playwright auto heal?
Common mistakes include over-relying on auto heal, using weak selectors, and ignoring logs. Auto heal works best when combined with robust locator strategies and periodic test review. Ignoring failures or skipping locator updates can hide real issues and reduce confidence in test results.
Can auto heal replace manual test maintenance?
Auto heal reduces maintenance for minor locator changes but cannot replace thoughtful test design. Complex UI changes, layout refactoring, or feature updates still require human intervention. Treat auto heal as a safety net rather than a substitute for regular test review and refactoring.
How do I enable auto heal in Playwright tests?
Enabling auto heal involves activating Playwright’s experimental features or plugins designed for locator repair. Once enabled, failing selectors trigger analysis for alternatives, and the system updates locators dynamically. Proper setup ensures minimal disruption to test execution while improving reliability.
Does auto heal work with all selector types in Playwright?
Auto heal works best with robust selector types such as CSS, text, and XPath. Some dynamic or highly transient selectors may still fail, requiring human review. Understanding selector stability helps in predicting where auto heal will succeed and where manual updates are unavoidable.
How does auto heal handle multiple matching elements?
When multiple elements match a locator, Playwright auto heal prioritizes based on similarity to the original target, such as text content, attributes, or DOM position. This reduces false matches but requires careful test design to avoid ambiguous elements that could cause unpredictable behavior.
Can auto heal improve CI/CD test reliability?
Yes, auto heal significantly improves reliability in CI/CD pipelines where frequent UI changes can break tests. By dynamically adapting to minor locator shifts, it reduces false failures, allowing teams to detect real issues faster, maintain stable builds, and reduce developer frustration.

Did you find this page helpful?

Helpful

NotHelpful

More Related Hubs

ShadowLT Logo

Start your journey with LambdaTest

Get 100 minutes of automation test minutes FREE!!

Signup for free