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/locators.md

View on GitHub
# Locator Strategies

## Table of Contents

1. [Priority Order](#priority-order)
2. [User-Facing Locators](#user-facing-locators)
3. [Filtering & Chaining](#filtering--chaining)
4. [Dynamic Content](#dynamic-content)
5. [Shadow DOM](#shadow-dom)
6. [Iframes](#iframes)

## Priority Order

Use locators in this order of preference:

1. **Role-based** (most resilient): `getByRole`
2. **Label-based**: `getByLabel`, `getByPlaceholder`
3. **Text-based**: `getByText`, `getByTitle`
4. **Test IDs** (when semantic locators aren't possible): `getByTestId`
5. **CSS/XPath** (last resort): `locator('css=...')`, `locator('xpath=...')`

## User-Facing Locators

### getByRole

Most robust approach - matches how users and assistive technology perceive the page.

```typescript
// Buttons
page.getByRole('button', { name: 'Submit', exact: true }); // exact accessible name
page.getByRole('button', { name: /submit/i }); // flexible case-insensitive match

// Links
page.getByRole('link', { name: 'Home' });

// Form elements
page.getByRole('textbox', { name: 'Email' });
page.getByRole('checkbox', { name: 'Remember me' });
page.getByRole('combobox', { name: 'Country' });
page.getByRole('radio', { name: 'Option A' });

// Headings
page.getByRole('heading', { name: 'Welcome', level: 1 });

// Lists & items
page.getByRole('list').getByRole('listitem');

// Navigation & regions
page.getByRole('navigation');
page.getByRole('main');
page.getByRole('dialog');
page.getByRole('alert');
```

### getByLabel

For form elements with associated labels.

```typescript
// Input with <label for="email">
page.getByLabel('Email address');

// Input with aria-label
page.getByLabel('Search');

// Exact match
page.getByLabel('Email', { exact: true });
```

### getByPlaceholder

```typescript
page.getByPlaceholder('Enter your email');
page.getByPlaceholder(/email/i);
```

### getByText

```typescript
// Partial match (default)
page.getByText('Welcome');

// Exact match
page.getByText('Welcome to our site', { exact: true });

// Regex
page.getByText(/welcome/i);
```

### getByTestId

Configure custom test ID attribute in `playwright.config.ts`:

```typescript
use: {
	testIdAttribute: 'data-testid'; // default
}
```

Usage:

```typescript
// HTML: <button data-testid="submit-btn">Submit</button>
page.getByTestId('submit-btn');
```

## Filtering & Chaining

### filter()

Narrow down locators:

```typescript
// Filter by text
page.getByRole('listitem').filter({ hasText: 'Product' });

// Filter by NOT having text
page.getByRole('listitem').filter({ hasNotText: 'Out of stock' });

// Filter by child locator
page.getByRole('listitem').filter({
	has: page.getByRole('button', { name: 'Buy' })
});

// Combine filters
page.getByRole('listitem')
	.filter({ hasText: 'Product' })
	.filter({ has: page.getByText('$9.99') });
```

### Chaining

```typescript
// Navigate down the DOM tree
page.getByRole('article').getByRole('heading');

// Get parent/ancestor
page.getByText('Child').locator('..');
page.getByText('Child').locator('xpath=ancestor::article');
```

### nth() and first()/last()

```typescript
page.getByRole('listitem').first();
page.getByRole('listitem').last();
page.getByRole('listitem').nth(2); // 0-indexed
```

## Dynamic Content

### Waiting for Elements

Locators auto-wait for actionability by default. For explicit state waiting:

```typescript
await page.getByRole('button').waitFor({ state: 'visible' });
await page.getByText('Loading').waitFor({ state: 'hidden' });
```

> **For comprehensive waiting strategies** (element state, navigation, network, polling with `toPass()`), see [assertions-waiting.md](assertions-waiting.md#waiting-strategies).

### Lists with Dynamic Items

```typescript
// Wait for specific count
await expect(page.getByRole('listitem')).toHaveCount(5);

// Get all matching elements
const items = await page.getByRole('listitem').all();
for (const item of items) {
	await expect(item).toBeVisible();
}
```

## Shadow DOM

Playwright pierces shadow DOM by default:

```typescript
// Automatically finds elements inside shadow roots
page.getByRole('button', { name: 'Shadow Button' });

// Explicit shadow DOM traversal (if needed)
page.locator('my-component').locator('internal:shadow=button');
```

## Iframes

```typescript
// By frame name or URL
const frame = page.frameLocator('iframe[name="content"]');
await frame.getByRole('button').click();

// By index
const frame = page.frameLocator('iframe').first();

// Nested iframes
const nestedFrame = page.frameLocator('#outer').frameLocator('#inner');
await nestedFrame.getByText('Content').click();
```

## Debugging Locators

```typescript
// Highlight element in headed mode
await page.getByRole('button').highlight();

// Count matches
const count = await page.getByRole('listitem').count();

// Check if exists without waiting
const exists = (await page.getByRole('button').count()) > 0;

// Use Playwright Inspector
// PWDEBUG=1 npx playwright test
```

## Common Issues & Solutions

| Issue                   | Solution                                         |
| ----------------------- | ------------------------------------------------ |
| Multiple elements match | Add filters or use `nth()`, `first()`, `last()`  |
| Element not found       | Check visibility, wait for load, verify selector |
| Stale element           | Locators are lazy; re-query if DOM changes       |
| Dynamic IDs             | Use stable attributes like role, text, test-id   |
| Hidden elements         | Use `{ force: true }` only when necessary        |

## Anti-Patterns to Avoid

| Anti-Pattern                      | Problem                           | Solution                                          |
| --------------------------------- | --------------------------------- | ------------------------------------------------- |
| `page.locator('.btn-primary')`    | Brittle, implementation-dependent | `page.getByRole('button', { name: 'Submit' })`    |
| `page.locator('#dynamic-id-123')` | Breaks when IDs change            | Use stable attributes like role, text, or test-id |
| Testing implementation details    | Breaks on refactoring             | Test user-visible behavior                        |

## Related References

- **Debugging selector issues**: See [debugging.md](../debugging/debugging.md) for troubleshooting
- **Waiting for elements**: See [assertions-waiting.md](assertions-waiting.md) for waiting strategies
- **Using in Page Objects**: See [page-object-model.md](page-object-model.md) for organizing locators
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