Skip to main content
skill CX Codex

Playwright · gentleman-programming — Claude Code skill: E2E tests with Page Objects

Skill for writing E2E tests on Playwright using the Page Objects pattern. Guides you through exploring real UI with MCP tools first, then writing selectors and assertions based on actual page structure.

Apache-2.0 194 installs ★ 678 updated 2026-03-28

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add Gentleman-Programming/Gentleman-Skills --skill playwright -a claude-code
Open on GitHub

What playwright does

The skill enforces a methodical workflow: navigate to the target page and capture snapshots via MCP tools (if available) to discover real selectors and user actions before writing test code. It includes a Page Object Model template with a base class for shared methods, a selector priority system (getByRole and getByLabel before CSS), and file organization rules—all tests for one page go in a single spec file paired with its page object.

It promotes refactoring: duplicate UI interactions like waiting for notifications move to BasePage; test data generation, setup, and teardown utilities go to helpers.ts. Assumes Playwright and Python are already set up in your project.

What it helps with

  • write E2E tests based on real DOM, not assumptions
  • organize Page Objects to avoid duplicating common methods across pages
  • pick the right selector: accessibility role, form label, or testId
  • reuse page objects from different pages in a single test scenario
  • split concerns between page objects, test utilities, and data generators

Example prompts for the agent

  • Write an E2E test for login flow that verifies redirect to dashboard after sign-in
  • Add a test to validate the signup form requires @ in the email field
  • Create a Page Object for a modal dialog, extract selectors using Playwright MCP tools

How to install playwright

1Skills CLI (Vercel)

npx skills add Gentleman-Programming/Gentleman-Skills --skill playwright -a claude-code

2Manually: put the files in place

~/.claude/skills/playwright/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/playwright/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about playwright

How do I install Playwright in Claude Code?

Run npx skills add Gentleman-Programming/Gentleman-Skills --skill playwright -a claude-code, then open ~/.claude/skills/playwright/SKILL.md. Make sure Playwright and Python are installed in your project.

What does this skill teach?

Patterns for writing E2E tests: explore pages with MCP tools first, extract selectors, structure Page Objects, share common methods via BasePage and helpers.ts, and follow selector priority rules.

When should I use Playwright MCP tools?

Before writing a test: navigate to the page, take a snapshot to see the structure, interact with elements, capture screenshots of different states. This gives you exact selectors and confirms the user flow works as expected. Skip to code-based tests if MCP is unavailable.

Source text

SKILL.md · Apache-2.0
---
name: playwright
description: >
  Playwright E2E testing patterns.
  Trigger: When writing E2E tests - Page Objects, selectors, MCP workflow.
license: Apache-2.0
metadata:
  author: gentleman-programming
  version: "1.1"
---

## MCP Workflow (MANDATORY If Available)

**⚠️ If you have Playwright MCP tools, ALWAYS use them BEFORE creating any test:**

1. **Navigate** to target page
2. **Take snapshot** to see page structure and elements
3. **Interact** with forms/elements to verify exact user flow
4. **Take screenshots** to document expected states
5. **Verify page transitions** through complete flow (loading, success, error)
6. **Document actual selectors** from snapshots (use real refs and labels)
7. **Only after exploring** create test code with verified selectors

**If MCP NOT available:** Proceed with test creation based on docs and code analysis.

**Why This Matters:**
- ✅ Precise tests - exact steps needed, no assumptions
- ✅ Accurate selectors - real DOM structure, not imagined
- ✅ Real flow validation - verify journey actually works
- ✅ Avoid over-engineering - minimal tests for what exists
- ✅ Prevent flaky tests - real exploration = stable tests
- ❌ Never assume how UI "should" work

## File Structure

```
tests/
├── base-page.ts              # Parent class for ALL pages
├── helpers.ts                # Shared utilities
└── {page-name}/
    ├── {page-name}-page.ts   # Page Object Model
    ├── {page-name}.spec.ts   # ALL tests here (NO separate files!)
    └── {page-name}.md        # Test documentation
```

**File Naming:**
- ✅ `sign-up.spec.ts` (all sign-up tests)
- ✅ `sign-up-page.ts` (page object)
- ✅ `sign-up.md` (documentation)
- ❌ `sign-up-critical-path.spec.ts` (WRONG - no separate files)
- ❌ `sign-up-validation.spec.ts` (WRONG)

## Selector Priority (REQUIRED)

```typescript
// 1. BEST - getByRole for interactive elements
this.submitButton = page.getByRole("button", { name: "Submit" });
this.navLink = page.getByRole("link", { name: "Dashboard" });

// 2. BEST - getByLabel for form controls
this.emailInput = page.getByLabel("Email");
this.passwordInput = page.getByLabel("Password");

// 3. SPARINGLY - getByText for static content only
this.errorMessage = page.getByText("Invalid credentials");
this.pageTitle = page.getByText("Welcome");

// 4. LAST RESORT - getByTestId when above fail
this.customWidget = page.getByTestId("date-picker");

// ❌ AVOID fragile selectors
this.button = page.locator(".btn-primary");  // NO
this.input = page.locator("#email");         // NO
```

## Scope Detection (ASK IF AMBIGUOUS)

| User Says | Action |
|-----------|--------|
| "a test", "one test", "new test", "add test" | Create ONE test() in existing spec |
| "comprehensive tests", "all tests", "test suite", "generate tests" | Create full suite |

**Examples:**
- "Create a test for user sign-up" → ONE test only
- "Generate E2E tests for login page" → Full suite
- "Add a test to verify form validation" → ONE test to existing spec

## Page Object Pattern

```typescript
import { Page, Locator, expect } from "@playwright/test";

// BasePage - ALL pages extend this
export class BasePage {
  constructor(protected page: Page) {}

  async goto(path: string): Promise<void> {
    await this.page.goto(path);
    await this.page.waitForLoadState("networkidle");
  }

  // Common methods go here (see Refactoring Guidelines)
  async waitForNotification(): Promise<void> {
    await this.page.waitForSelector('[role="status"]');
  }

  async verifyNotificationMessage(message: string): Promise<void> {
    const notification = this.page.locator('[role="status"]');
    await expect(notification).toContainText(message);
  }
}

// Page-specific implementation
export interface LoginData {
  email: string;
  password: string;
}

export class LoginPage extends BasePage {
  readonly emailInput: Locator;
  readonly passwordInput: Locator;
  readonly submitButton: Locator;

  constructor(page: Page) {
    super(page);
    this.emailInput = page.getByLabel("Email");
    this.passwordInput = page.getByLabel("Password");
    this.submitButton = page.getByRole("button", { name: "Sign in" });
  }

  async goto(): Promise<void> {
    await super.goto("/login");
  }

  async login(data: LoginData): Promise<void> {
    await this.emailInput.fill(data.email);
    await this.passwordInput.fill(data.password);
    await this.submitButton.click();
  }

  async verifyCriticalOutcome(): Promise<void> {
    await expect(this.page).toHaveURL("/dashboard");
  }
}
```

## Page Object Reuse (CRITICAL)

**Always check existing page objects before creating new ones!**

```typescript
// ✅ GOOD: Reuse existing page objects
import { SignInPage } from "../sign-in/sign-in-page";
import { HomePage } from "../home/home-page";

test("User can sign up and login", async ({ page }) => {
  const signUpPage = new SignUpPage(page);
  const signInPage = new SignInPage(page);  // REUSE
  const homePage = new HomePage(page);      // REUSE

  await signUpPage.signUp(userData);
  await homePage.verifyPageLoaded();  // REUSE method
  await homePage.signOut();           // REUSE method
  await signInPage.login(credentials); // REUSE method
});

// ❌ BAD: Recreating existing functionality
export class SignUpPage extends BasePage {
  async logout() { /* ... */ }  // ❌ HomePage already has this
  async login() { /* ... */ }   // ❌ SignInPage already has this
}
```

**Guidelines:**
- Check `tests/` for existing page objects first
- Import and reuse existing pages
- Create page objects only when page doesn't exist
- If test requires multiple pages, ensure all page objects exist (create if needed)

## Refactoring Guidelines

### Move to `BasePage` when:
- ✅ Navigation helpers used by multiple pages (`waitForPageLoad()`, `getCurrentUrl()`)
- ✅ Common UI interactions (notifications, modals, theme toggles)
- ✅ Verification patterns repeated across pages (`isVisible()`, `waitForVisible()`)
- ✅ Error handling that applies to all pages
- ✅ Screenshot utilities for debugging

### Move to `helpers.ts` when:
- ✅ Test data generation (`generateUniqueEmail()`, `generateTestUser()`)
- ✅ Setup/teardown utilities (`createTestUser()`, `cleanupTestData()`)
- ✅ Custom assertions (`expectNotificationToContain()`)
- ✅ API helpers for test setup (`seedDatabase()`, `resetState()`)
- ✅ Time utilities (`waitForCondition()`, `retryAction()`)

**Before (BAD):**
```typescript
// Repeated in multiple page objects
export class SignUpPage extends BasePage {
  async waitForNotification(): Promise<void> {
    await this.page.waitForSelector('[role="status"]');
  }
}
export class SignInPage extends BasePage {
  async waitForNotification(): Promise<void> {
    await this.page.waitForSelector('[role="status"]');  // DUPLICATED!
  }
}
```

**After (GOOD):**
```typescript
// BasePage - shared across all pages
export class BasePage {
  async waitForNotification(): Promise<void> {
    await this.page.waitForSelector('[role="status"]');
  }
}

// helpers.ts - data generation
export function generateUniqueEmail(): string {
  return `test.${Date.now()}@example.com`;
}

export function generateTestUser() {
  return {
    name: "Test User",
    email: generateUniqueEmail(),
    password: "TestPassword123!",
  };
}
```

## Test Pattern with Tags

```typescript
import { test, expect } from "@playwright/test";
import { LoginPage } from "./login-page";

test.describe("Login", () => {
  test("User can login successfully",
    { tag: ["@critical", "@e2e", "@login", "@LOGIN-E2E-001"] },
    async ({ page }) => {
      const loginPage = new LoginPage(page);

      await loginPage.goto();
      await loginPage.login({ email: "[email protected]", password: "pass123" });

      await expect(page).toHaveURL("/dashboard");
    }
  );
});
```

**Tag Categories:**
- Priority: `@critical`, `@high`, `@medium`, `@low`
- Type: `@e2e`
- Feature: `@signup`, `@signin`, `@dashboard`
- Test ID: `@SIGNUP-E2E-001`, `@LOGIN-E2E-002`

## Test Documentation Format ({page-name}.md)

```markdown
### E2E Tests: {Feature Name}

**Suite ID:** `{SUITE-ID}`
**Feature:** {Feature description}

---

## Test Case: `{TEST-ID}` - {Test case title}

**Priority:** `{critical|high|medium|low}`

**Tags:**
- type → @e2e
- feature → @{feature-name}

**Description/Objective:** {Brief description}

**Preconditions:**
- {Prerequisites for test to run}
- {Required data or state}

### Flow Steps:
1. {Step 1}
2. {Step 2}
3. {Step 3}

### Expected Result:
- {Expected outcome 1}
- {Expected outcome 2}

### Key verification points:
- {Assertion 1}
- {Assertion 2}

### Notes:
- {Additional considerations}
```

**Documentation Rules:**
- ❌ NO general test running instructions
- ❌ NO file structure explanations
- ❌ NO code examples or tutorials
- ❌ NO troubleshooting sections
- ✅ Focus ONLY on specific test case
- ✅ Keep under 60 lines when possible

## Commands

```bash
npx playwright test                    # Run all
npx playwright test --grep "login"     # Filter by name
npx playwright test --ui               # Interactive UI
npx playwright test --debug            # Debug mode
npx playwright test tests/login/       # Run specific folder
```

## Keywords
playwright, e2e, testing, page object model, selectors, end-to-end, mcp

© gentleman-programming · Apache-2.0 · Gentleman-Programming/Gentleman-Skills

Similar skills

All skills for Testing and QA →

playwright by other authors comes first.

playwright secondsky A Playwright skill for browser automation and end-to-end testing. It finds your running dev server and writes the test script for the task. CX Codex +1 1,100installs playwright Mindrally playwright — a skill for automating E2E testing of web applications in TypeScript and JavaScript. Teaches agents to write tests following best practices: resilient locators, web-first assertions, no hardcoded timeouts. CX Codex +1 1,100installs playwright PyModel A skill for Claude Code and Codex with Playwright testing rules for Next.js apps. Runs when writing new E2E tests, fixing flaky failures, or tuning CI pipelines. CX Codex +1 623installs playwright bobmatnyc A Playwright skill that guides the agent through writing end-to-end tests: locators, auto-wait, cross-browser runs. Useful when user flows need test coverage. CX Codex +1 930installs playwright oakoss Teaches your agent the Playwright API: locators, assertions, screenshots and PDFs, stealth mode, authenticated sessions, error fixes. CX Codex +1 476installs playwright-testing alinaqi playwright-testing — a Playwright E2E skill: page objects, a locator order that starts with roles, and a config running chromium, firefox, webkit plus mobile viewports. CX Codex +1 3,400installs cypress-playwright-setup patricio0312rev cypress-playwright-setup — a skill for Claude Code, Codex, Cursor, and other agents that sets up E2E testing with Cypress or Playwright: page objects, fixtures, and CI integration. CX Codex +1 313installs playwright-pro borghei playwright-pro — a skill for Claude Code, Codex, and Cursor. Generates Playwright end-to-end tests, builds Page Object structures, diagnoses flaky runs, and migrates suites from Cypress or Selenium. CX Codex +1 148installs playwright-skill testdino.com Supplies the agent with 79 reference guides for Playwright 1.64 across TypeScript and JavaScript. Helps write tests, investigate CI failures, configure mocking, and stabilize flaky suites. CX Codex +1 6,200installs playwright-expert https://github.com/Jeffallan playwright-expert sets up Playwright E2E testing infrastructure, writes Page Object Model classes, and troubleshoots flaky tests using trace inspection. CX Codex +1 5,700installs playwright-cursor-rules Mindrally Trains the agent to write Playwright end-to-end tests following QA automation standards: stable locators, isolation, parallel execution. CX Codex +1 738installs

From the same set20

The whole set →
hexagonal-architecture-layers-java The hexagonal-architecture-layers-java skill structures Java services around Domain, Application, and Infrastructure layers. Use it for new services or Spring refactoring. CX Codex +1 250installs angular-core angular-core — a skill that teaches the agent modern Angular patterns: standalone components, signals instead of hooks, zoneless mode, and native control flow. CX Codex +1 230installs jira-task Generates structured Jira tasks following Prowler's format. Handles bug reports, feature requests, and refactoring work with proper titles, acceptance criteria, and component-based splitting. CX Codex +1 217installs github-pr github-pr guides AI agents to format pull requests using Conventional Commits and GitHub CLI commands. CX Codex +1 205installs elixir-antipatterns elixir-antipatterns is a Claude Code skill that guides code reviews, Ecto query tuning, and Phoenix refactoring with a catalog of 8 anti-patterns. CX Codex +1 194installs nextjs-15 Supplies Next.js 15 App Router patterns covering file conventions, Server Actions, parallel data fetching, and middleware. CX Codex +1 185installs electron Guides desktop app development in Electron with secure IPC patterns, typed channels, and clear separation between main and renderer processes. CX Codex +1 175installs skill-creator skill-creator builds new AI agent skills against the Agent Skills spec. Use it for recurring patterns, project rules, and workflows that need explicit steps. CX Codex +1 171installs

Project sponsors

Companies that keep this analytics open