DEV Community

Aswani Kumar
Aswani Kumar

Posted on

πŸš‘ Creating a Self-Healing Automation Framework with Playwright

🧠 What is a Self-Healing Automation Framework?

A self-healing test framework can automatically detect and recover from broken locators or test failures β€” reducing test flakiness and manual maintenance effort.

Instead of failing immediately when a selector is not found, the framework:

  • Detects similar or alternate selectors intelligently.
  • Applies fallback strategies to continue execution.
  • Logs the issue for review and permanent fix.

πŸš€ Why Use Playwright for Self-Healing?

Playwright, by design, offers:

  • Robust locator strategies (e.g., getByRole, getByText, nth, etc.).
  • Auto-waiting mechanism for stability.
  • Built-in retries for flaky steps.

This makes it a perfect base for adding self-healing intelligence on top.


πŸ—οΈ Architecture of a Self-Healing Playwright Framework

Here’s the high-level design you can follow:

Test Scripts
   |
   v
Custom Locator Wrapper (with Healing Logic)
   |
   v
Locator Engine (Playwright)
Enter fullscreen mode Exit fullscreen mode

Key Components:

  1. Locator Map: A JSON or database file that stores element selectors with possible alternatives.
  2. Smart Wrapper: A utility that tries primary and fallback locators in sequence.
  3. Logging Layer: To log failed attempts, auto-fixes, and suggestions.
  4. AI/ML Module (Optional): Use AI to suggest closest matches if none are found.

πŸ› οΈ Code Implementation (Simplified Example)

πŸ“ locatorMap.ts (Locator Store)

export const locatorMap = {
  "loginButton": [
    "//button[text()='Login']",
    "//button[contains(@class, 'btn-login')]",
    "button:has-text('Sign In')"
  ],
  "usernameInput": [
    "input[name='username']",
    "#user",
    "//input[@placeholder='Username']"
  ]
};
Enter fullscreen mode Exit fullscreen mode

πŸ“ healingLocator.ts (Wrapper Function)

import { Page } from '@playwright/test';
import { locatorMap } from './locatorMap';

export async function findWithHealing(page: Page, key: string) {
  const locators = locatorMap[key];

  for (const locator of locators) {
    try {
      const element = page.locator(locator);
      if (await element.count() > 0) {
        console.log(`[Healed] Found "${key}" using: ${locator}`);
        return element;
      }
    } catch (err) {
      continue;
    }
  }

  throw new Error(`Element "${key}" not found via any fallback`);
}
Enter fullscreen mode Exit fullscreen mode

βœ… Usage in Tests

import { test } from '@playwright/test';
import { findWithHealing } from './healingLocator';

test('Login flow with healing selectors', async ({ page }) => {
  await page.goto('https://example.com/login');

  const username = await findWithHealing(page, 'usernameInput');
  await username.fill('aswani');

  const loginBtn = await findWithHealing(page, 'loginButton');
  await loginBtn.click();
});
Enter fullscreen mode Exit fullscreen mode

🧩 Bonus: AI-Based Self-Healing (Optional Layer)

For advanced teams, integrate AI tools like OpenAI or fuzzy string matching to:

  • Suggest closest matching elements.
  • Auto-learn updated selectors from DOM diffs.
  • Store successful fallback attempts for self-learning.

πŸ‘‰ Example prompt to GPT:

β€œSuggest an alternate selector for a missing button labeled β€˜Login’ in a changed DOM structure.”


πŸ“Š Benefits of Self-Healing Framework

  • πŸ”„ Reduced Test Failures due to DOM changes.
  • πŸ’‘ Proactive Maintenance with fallback logging.
  • πŸ“‰ Lower Maintenance Cost and manual rework.
  • ⏱️ Faster Feedback Loops in CI/CD pipelines.
  • πŸ€– Better Stability in Agile Teams that release often.

🚨 When NOT to Use Self-Healing

Self-healing is a safety net, not a permanent bandage.

Avoid using it:

  • As a replacement for good test design.
  • When the application is still evolving rapidly.
  • If false positives can harm critical workflows.

πŸ“Œ Final Thoughts

A self-healing Playwright framework bridges the gap between rapid development and test stability. While it won’t replace smart test design, it adds resilience to your automation suite.

If your QA team is struggling with flaky tests, try implementing this approach. Start simple, monitor results, and expand with AI if needed.


πŸ’¬ What’s Next?

βœ… Want a GitHub template for this self-healing setup? Drop a comment below.

πŸ“© Have questions about integrating AI with Playwright? Let’s connect!


πŸ“ GitHub Project Structure (Planned)

We will provide a full working Playwright project with:

  • A main branch: Standard test automation setup.
  • A self-healing branch: Enhanced with fallback locator support.
  • Demo tests using a public login form.

πŸ”— GitHub link coming soon β€” follow for updates!

Top comments (1)

Collapse
 
shiwei_xie_24a93f54203fb3 profile image
shiwei xie

TextStow could be useful for this workflow β€” clipboard history + reusable favorites + prompt templates + cleanup for JSON/PDF/URLs. Local-first, free: textstow.com