Skip to content

ever-co/ever-works / .agents/skills/playwright-best-practices

playwright-best-practices

Verified

Use when writing Playwright tests, fixing flaky tests, debugging failures, implementing Page Object Model, configuring CI/CD, optimizing performance, mocking APIs, handling authentication or OAuth, testing accessibility (axe-core), file uploads/downloads, date/time mocking, WebSockets, geolocation, permissions, multi-tab/popup flows, mobile/responsive layouts, touch gestures, GraphQL, error handling, offline mode, multi-user collaboration, third-party services (payments, email verification), console error monitoring, global setup/teardown, test annotations (skip, fixme, slow), test tags (@smoke, @fast, @critical, filtering with --grep), project dependencies, security testing (XSS, CSRF, auth), performance budgets (Web Vitals, Lighthouse), iframes, component testing, canvas/WebGL, service workers/PWA, test coverage, i18n/localization, Electron apps, or browser extension testing. Covers E2E, component, API, visual, accessibility, security, Electron, and extension testing.

FileKindSize
LICENSE.mdmarkdown1.0 KB
README.mdmarkdown9.9 KB
SKILL.mdskill md25.7 KB
advanced/authentication-flows.mdmarkdown10.4 KB
advanced/authentication.mdmarkdown29.4 KB
advanced/clock-mocking.mdmarkdown9.4 KB
advanced/mobile-testing.mdmarkdown10.3 KB
advanced/multi-context.mdmarkdown8.2 KB
advanced/multi-user.mdmarkdown10.9 KB
advanced/network-advanced.mdmarkdown10.1 KB
advanced/third-party.mdmarkdown11.1 KB
architecture/pom-vs-fixtures.mdmarkdown11.4 KB
architecture/test-architecture.mdmarkdown14.3 KB
architecture/when-to-mock.mdmarkdown11.9 KB
browser-apis/browser-apis.mdmarkdown10.1 KB
browser-apis/iframes.mdmarkdown11.1 KB
browser-apis/service-workers.mdmarkdown13.1 KB
browser-apis/websockets.mdmarkdown9.9 KB
core/annotations.mdmarkdown10.4 KB
core/assertions-waiting.mdmarkdown9.1 KB
core/configuration.mdmarkdown13.7 KB
core/fixtures-hooks.mdmarkdown11.2 KB
core/global-setup.mdmarkdown12.4 KB
core/locators.mdmarkdown6.4 KB
core/page-object-model.mdmarkdown7.7 KB
core/projects-dependencies.mdmarkdown8.1 KB
core/test-data.mdmarkdown11.3 KB
core/test-suite-structure.mdmarkdown9.1 KB
core/test-tags.mdmarkdown6.7 KB
debugging/console-errors.mdmarkdown9.3 KB
debugging/debugging.mdmarkdown14.7 KB
debugging/error-testing.mdmarkdown9.2 KB
debugging/flaky-tests.mdmarkdown14.5 KB
frameworks/angular.mdmarkdown18.9 KB
frameworks/nextjs.mdmarkdown13.4 KB
frameworks/react.mdmarkdown17.5 KB
frameworks/vue.mdmarkdown17.3 KB
infrastructure-ci-cd/ci-cd.mdmarkdown10.4 KB
infrastructure-ci-cd/docker.mdmarkdown7.0 KB
infrastructure-ci-cd/github-actions.mdmarkdown15.1 KB
infrastructure-ci-cd/gitlab.mdmarkdown10.9 KB
infrastructure-ci-cd/other-providers.mdmarkdown14.2 KB
infrastructure-ci-cd/parallel-sharding.mdmarkdown11.6 KB
infrastructure-ci-cd/performance.mdmarkdown11.3 KB
infrastructure-ci-cd/reporting.mdmarkdown11.4 KB
infrastructure-ci-cd/test-coverage.mdmarkdown12.0 KB
testing-patterns/accessibility.mdmarkdown8.7 KB
testing-patterns/api-testing.mdmarkdown23.5 KB
testing-patterns/browser-extensions.mdmarkdown13.0 KB
testing-patterns/canvas-webgl.mdmarkdown12.3 KB
testing-patterns/component-testing.mdmarkdown11.0 KB
testing-patterns/drag-drop.mdmarkdown17.4 KB
testing-patterns/electron.mdmarkdown12.8 KB
testing-patterns/file-operations.mdmarkdown10.0 KB
testing-patterns/file-upload-download.mdmarkdown16.5 KB
testing-patterns/forms-validation.mdmarkdown21.3 KB
testing-patterns/graphql-testing.mdmarkdown8.6 KB
testing-patterns/i18n.mdmarkdown12.3 KB
testing-patterns/performance-testing.mdmarkdown11.5 KB
testing-patterns/security-testing.mdmarkdown11.5 KB
testing-patterns/visual-regression.mdmarkdown18.4 KB

core/page-object-model.md

View on GitHub
# Page Object Model (POM)

## Table of Contents

1. [Overview](#overview)
2. [Basic Structure](#basic-structure)
3. [Component Objects](#component-objects)
4. [Composition Patterns](#composition-patterns)
5. [Factory Functions](#factory-functions)
6. [Best Practices](#best-practices)

## Overview

Page Object Model encapsulates page structure and interactions, providing:

- **Maintainability**: Change selectors in one place
- **Reusability**: Share page interactions across tests
- **Readability**: Tests express intent, not implementation

## Basic Structure

### Page Class

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

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

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

	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);
	}
}
```

### Usage in Tests

```typescript
// tests/login.spec.ts
import { test, expect } from '@playwright/test';
import { LoginPage } from '../pages/login.page';

test.describe('Login', () => {
	test('successful login redirects to dashboard', async ({ page }) => {
		const loginPage = new LoginPage(page);
		await loginPage.goto();
		await loginPage.login('user@example.com', 'password123');
		await expect(page).toHaveURL('/dashboard');
	});

	test('shows error for invalid credentials', async ({ page }) => {
		const loginPage = new LoginPage(page);
		await loginPage.goto();
		await loginPage.login('invalid@example.com', 'wrong');
		await loginPage.expectError('Invalid credentials');
	});
});
```

## Component Objects

For reusable UI components:

```typescript
// components/navbar.component.ts
import { Page, Locator } from '@playwright/test';

export class NavbarComponent {
	readonly container: Locator;
	readonly logo: Locator;
	readonly searchInput: Locator;
	readonly userMenu: Locator;

	constructor(page: Page) {
		this.container = page.getByRole('navigation');
		this.logo = this.container.getByRole('link', { name: 'Home' });
		this.searchInput = this.container.getByRole('searchbox');
		this.userMenu = this.container.getByRole('button', { name: /user menu/i });
	}

	async search(query: string) {
		await this.searchInput.fill(query);
		await this.searchInput.press('Enter');
	}

	async openUserMenu() {
		await this.userMenu.click();
	}
}
```

```typescript
// components/modal.component.ts
import { Locator, expect } from '@playwright/test';

export class ModalComponent {
	readonly container: Locator;
	readonly title: Locator;
	readonly closeButton: Locator;
	readonly confirmButton: Locator;

	constructor(container: Locator) {
		this.container = container;
		this.title = container.getByRole('heading');
		this.closeButton = container.getByRole('button', { name: 'Close' });
		this.confirmButton = container.getByRole('button', { name: 'Confirm' });
	}

	async expectTitle(title: string) {
		await expect(this.title).toHaveText(title);
	}

	async close() {
		await this.closeButton.click();
	}

	async confirm() {
		await this.confirmButton.click();
	}
}
```

## Composition Patterns

### Page with Components

```typescript
// pages/dashboard.page.ts
import { Page, Locator } from '@playwright/test';
import { NavbarComponent } from '../components/navbar.component';
import { ModalComponent } from '../components/modal.component';

export class DashboardPage {
	readonly page: Page;
	readonly navbar: NavbarComponent;
	readonly newProjectButton: Locator;

	constructor(page: Page) {
		this.page = page;
		this.navbar = new NavbarComponent(page);
		this.newProjectButton = page.getByRole('button', { name: 'New Project' });
	}

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

	async createProject() {
		await this.newProjectButton.click();
		return new ModalComponent(this.page.getByRole('dialog'));
	}
}
```

### Page Navigation

```typescript
// pages/base.page.ts
import { Page } from '@playwright/test';

export abstract class BasePage {
	constructor(readonly page: Page) {}

	abstract goto(): Promise<void>;

	async getTitle(): Promise<string> {
		return this.page.title();
	}
}
```

```typescript
// Return new page object on navigation
export class LoginPage extends BasePage {
	async login(email: string, password: string): Promise<DashboardPage> {
		await this.emailInput.fill(email);
		await this.passwordInput.fill(password);
		await this.submitButton.click();
		return new DashboardPage(this.page);
	}
}

// Usage
const loginPage = new LoginPage(page);
await loginPage.goto();
const dashboardPage = await loginPage.login('user@example.com', 'pass');
await dashboardPage.expectWelcomeMessage();
```

## Factory Functions

Alternative to classes for simpler pages:

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

export function createLoginPage(page: Page) {
	const emailInput = page.getByLabel('Email');
	const passwordInput = page.getByLabel('Password');
	const submitButton = page.getByRole('button', { name: 'Sign in' });

	return {
		goto: () => page.goto('/login'),
		login: async (email: string, password: string) => {
			await emailInput.fill(email);
			await passwordInput.fill(password);
			await submitButton.click();
		},
		emailInput,
		passwordInput,
		submitButton
	};
}

// Usage
const loginPage = createLoginPage(page);
await loginPage.goto();
await loginPage.login('user@example.com', 'password');
```

## Best Practices

### Do

- **Keep locators in page objects** - Single source of truth
- **Return new page objects** when navigation occurs
- **Expose elements** for custom assertions in tests
- **Use descriptive method names** - `submitOrder()` not `clickButton()`
- **Keep methods focused** - One action per method

### Don't

- **Don't include assertions in page methods** (usually) - Keep in tests
- **Don't expose implementation details** - Hide complex interactions
- **Don't make page objects too large** - Split into components
- **Don't share state** between page object instances

### Work Structure

```
tests/
├── pages/
│   ├── base.page.ts
│   ├── login.page.ts
│   ├── dashboard.page.ts
│   └── settings.page.ts
├── components/
│   ├── navbar.component.ts
│   ├── modal.component.ts
│   └── table.component.ts
├── fixtures/
│   └── pages.fixture.ts
└── specs/
    ├── login.spec.ts
    └── dashboard.spec.ts
```

### Using with Fixtures

```typescript
// fixtures/pages.fixture.ts
import { test as base } from '@playwright/test';
import { LoginPage } from '../pages/login.page';
import { DashboardPage } from '../pages/dashboard.page';

type Pages = {
	loginPage: LoginPage;
	dashboardPage: DashboardPage;
};

export const test = base.extend<Pages>({
	loginPage: async ({ page }, use) => {
		await use(new LoginPage(page));
	},
	dashboardPage: async ({ page }, use) => {
		await use(new DashboardPage(page));
	}
});

// Usage in tests
test('can login', async ({ loginPage }) => {
	await loginPage.goto();
	await loginPage.login('user@example.com', 'password');
});
```

## Related References

- **Locator strategies**: See [locators.md](locators.md) for selecting elements
- **Fixtures**: See [fixtures-hooks.md](fixtures-hooks.md) for advanced fixture patterns
- **Test organization**: See [test-suite-structure.md](test-suite-structure.md) for structuring test suites
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall