Claude
Skills
Sign in
Back

playwright-pro

Included with Lifetime
$97 forever

Production-grade end-to-end testing with Playwright. Covers test generation from user stories, page object patterns, locator strategy, flaky test diagnosis, Cypress/Selenium migration, CI integration, visual regression testing, and accessibility auditing. Use when writing E2E tests, fixing flaky tests, or migrating from Cypress/Selenium.

Cloud & DevOpsscripts

What this skill does

# Playwright Pro

**Tier:** POWERFUL
**Category:** Engineering / Testing
**Maintainer:** Claude Skills Team

## Overview

Production-grade end-to-end testing with Playwright. Generate tests from user stories, implement the Page Object pattern for maintainability, apply the correct locator strategy for resilient tests, diagnose and fix flaky tests, migrate from Cypress or Selenium, integrate with CI/CD, run visual regression tests, and perform accessibility audits. Enforces the 10 golden rules that eliminate 90% of E2E test failures.

## Sub-Skills

This skill uses compound sub-skill architecture. Each sub-skill in `skills/` handles a specific workflow:

| Sub-Skill | File | Purpose |
|-----------|------|---------|
| **Init** | `skills/init.md` | Bootstrap Playwright in a project -- install, configure, create first test |
| **Generate** | `skills/generate.md` | Generate test files from user stories or page descriptions |
| **Fix** | `skills/fix.md` | Diagnose and fix failing or flaky tests using trace analysis |
| **Migrate** | `skills/migrate.md` | Migrate from Cypress or Selenium to Playwright |
| **Review** | `skills/review.md` | Audit test quality, coverage gaps, and flaky test indicators |
| **Report** | `skills/report.md` | Generate execution reports from Playwright JSON output |
| **Coverage** | `skills/coverage.md` | Map tests to user stories, identify coverage gaps |
| **BrowserStack** | `skills/browserstack.md` | BrowserStack cloud integration for cross-browser testing |
| **TestRail** | `skills/testrail.md` | TestRail integration for test case management |

### Sub-Skill Flow

```
Init ──> Generate ──> Review ──> Fix (if needed)
                         │
                    Coverage ──> Generate (fill gaps)
                         │
                    Report ──> BrowserStack / TestRail
```

**Typical lifecycle:** Init sets up the project, Generate creates tests from stories, Review audits quality, Fix resolves failures, Coverage identifies gaps that feed back into Generate, and Report/BrowserStack/TestRail handle reporting and integration.

## Scripts

| Script | Purpose |
|--------|---------|
| `scripts/test_generator.py` | Generate Playwright test code from user story descriptions |
| `scripts/flaky_detector.py` | Analyze multiple CI runs to detect flaky test patterns |
| `scripts/coverage_mapper.py` | Map tests to user flows and identify coverage gaps |
| `scripts/page_object_generator.py` | Generate Page Object classes from HTML or selector lists |
| `scripts/test_analyzer.py` | Scan test files for anti-patterns and quality issues |
| `scripts/test_report_parser.py` | Parse Playwright JSON reports into summaries |

## Keywords

Playwright, E2E testing, end-to-end testing, page objects, flaky tests, test generation, Cypress migration, Selenium migration, visual regression, accessibility testing, CI integration

## 10 Golden Rules

These rules are non-negotiable. Following them eliminates 90% of E2E test failures.

1. **`getByRole()` over CSS/XPath** — resilient to markup changes
2. **Never `page.waitForTimeout()`** — use web-first assertions instead
3. **`expect(locator)` auto-retries; `expect(await locator.textContent())` does NOT**
4. **Isolate every test** — no shared state between tests
5. **`baseURL` in config** — zero hardcoded URLs in tests
6. **Retries: 2 in CI, 0 locally** — retries mask flakiness in dev
7. **Traces: `'on-first-retry'`** — rich debugging without slowdown
8. **Fixtures over globals** — `test.extend()` for shared setup
9. **One behavior per test** — multiple related assertions are fine
10. **Mock external services only** — never mock your own app

## Locator Priority (Most to Least Preferred)

```
1. getByRole('button', { name: 'Submit' })     — semantic, accessible
2. getByLabel('Email address')                   — form fields with labels
3. getByText('Welcome back')                     — visible text content
4. getByPlaceholder('Enter your email')          — inputs with placeholder
5. getByTestId('submit-button')                  — when no semantic option exists
6. page.locator('.submit-btn')                   — CSS as last resort
7. page.locator('//button[@type="submit"]')      — XPath: avoid entirely
```

### Why This Order Matters

```typescript
// FRAGILE: breaks when CSS class changes
await page.locator('.btn-primary-lg').click();

// FRAGILE: breaks when DOM structure changes
await page.locator('div > form > button:nth-child(2)').click();

// RESILIENT: survives refactors, tests what users see
await page.getByRole('button', { name: 'Create account' }).click();
```

## Configuration

### playwright.config.ts

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

export default defineConfig({
  testDir: './tests/e2e',
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 4 : undefined,
  reporter: process.env.CI
    ? [['html'], ['github'], ['json', { outputFile: 'test-results.json' }]]
    : [['html']],

  use: {
    baseURL: process.env.BASE_URL || 'http://localhost:3000',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
    video: 'retain-on-failure',
  },

  projects: [
    // Auth setup: runs once, shares state with all tests
    { name: 'setup', testMatch: /.*\.setup\.ts/ },

    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
      dependencies: ['setup'],
    },
    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
      dependencies: ['setup'],
    },
    {
      name: 'mobile-chrome',
      use: { ...devices['Pixel 5'] },
      dependencies: ['setup'],
    },
  ],

  webServer: {
    command: 'pnpm dev',
    url: 'http://localhost:3000',
    reuseExistingServer: !process.env.CI,
    timeout: 30000,
  },
});
```

## Page Object Pattern

```typescript
// pages/login.page.ts
import { type Page, type Locator, expect } from '@playwright/test';

export class LoginPage {
  readonly page: Page;
  readonly emailInput: Locator;
  readonly passwordInput: Locator;
  readonly submitButton: Locator;
  readonly errorMessage: Locator;
  readonly forgotPasswordLink: Locator;

  constructor(page: Page) {
    this.page = page;
    this.emailInput = page.getByLabel('Email address');
    this.passwordInput = page.getByLabel('Password');
    this.submitButton = page.getByRole('button', { name: 'Sign in' });
    this.errorMessage = page.getByRole('alert');
    this.forgotPasswordLink = page.getByRole('link', { name: 'Forgot password?' });
  }

  async goto() {
    await this.page.goto('/login');
  }

  async login(email: string, password: string) {
    await this.emailInput.fill(email);
    await this.passwordInput.fill(password);
    await this.submitButton.click();
  }

  async expectError(message: string) {
    await expect(this.errorMessage).toContainText(message);
  }

  async expectRedirectToDashboard() {
    await expect(this.page).toHaveURL(/\/dashboard/);
  }
}
```

```typescript
// pages/dashboard.page.ts
import { type Page, type Locator, expect } from '@playwright/test';

export class DashboardPage {
  readonly page: Page;
  readonly heading: Locator;
  readonly projectList: Locator;
  readonly createProjectButton: Locator;

  constructor(page: Page) {
    this.page = page;
    this.heading = page.getByRole('heading', { name: 'Dashboard' });
    this.projectList = page.getByRole('list', { name: 'Projects' });
    this.createProjectButton = page.getByRole('button', { name: 'New project' });
  }

  async expectLoaded() {
    await expect(this.heading).toBeVisible();
  }

  async getProjectCount() {
    return this.projectList.getByRole('listitem').count();
  }

  async createProject(name: string) {
    await this.createProjectButton.click();
    await this.page.getByLabel('Project name').fill(name);
    await this.page.getByRole('button', { name: 'Create' }).click();
  }
}
```

## Test Generation from User Stories

Given a user story, generate tests following this pat

Related in Cloud & DevOps