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/assertions-waiting.md

View on GitHub
# Assertions & Waiting

## Table of Contents

1. [Web-First Assertions](#web-first-assertions)
2. [Generic Assertions](#generic-assertions)
3. [Soft Assertions](#soft-assertions)
4. [Waiting Strategies](#waiting-strategies)
5. [Polling & Retrying](#polling--retrying)
6. [Custom Matchers](#custom-matchers)

## Web-First Assertions

Auto-retry until condition is met or timeout. Always prefer these over generic assertions.

### Locator Assertions

```typescript
import { expect } from '@playwright/test';

// Visibility
await expect(page.getByRole('button')).toBeVisible();
await expect(page.getByRole('button')).toBeHidden();
await expect(page.getByRole('button')).not.toBeVisible();

// Enabled/Disabled
await expect(page.getByRole('button')).toBeEnabled();
await expect(page.getByRole('button')).toBeDisabled();

// Text content
await expect(page.getByRole('heading')).toHaveText('Welcome');
await expect(page.getByRole('heading')).toHaveText(/welcome/i);
await expect(page.getByRole('heading')).toContainText('Welcome');

// Count
await expect(page.getByRole('listitem')).toHaveCount(5);

// Attributes
await expect(page.getByRole('link')).toHaveAttribute('href', '/home');
await expect(page.getByRole('img')).toHaveAttribute('alt', /logo/i);

// CSS
await expect(page.getByRole('button')).toHaveClass(/primary/);
await expect(page.getByRole('button')).toHaveCSS('color', 'rgb(0, 0, 255)');

// Input values
await expect(page.getByLabel('Email')).toHaveValue('user@example.com');
await expect(page.getByLabel('Email')).toBeEmpty();

// Focus
await expect(page.getByLabel('Email')).toBeFocused();

// Checked state
await expect(page.getByRole('checkbox')).toBeChecked();
await expect(page.getByRole('checkbox')).not.toBeChecked();

// Editable state
await expect(page.getByLabel('Name')).toBeEditable();
```

### Page Assertions

```typescript
// URL
await expect(page).toHaveURL('/dashboard');
await expect(page).toHaveURL(/\/dashboard/);

// Title
await expect(page).toHaveTitle('Dashboard - MyApp');
await expect(page).toHaveTitle(/dashboard/i);
```

### Response Assertions

```typescript
const response = await page.request.get('/api/users');
await expect(response).toBeOK();
await expect(response).not.toBeOK();
```

## Generic Assertions

Use for non-UI values. Do NOT retry - execute immediately.

```typescript
// Equality
expect(value).toBe(5);
expect(object).toEqual({ name: 'Test' });
expect(array).toContain('item');

// Truthiness
expect(value).toBeTruthy();
expect(value).toBeFalsy();
expect(value).toBeNull();
expect(value).toBeUndefined();
expect(value).toBeDefined();

// Numbers
expect(value).toBeGreaterThan(5);
expect(value).toBeLessThanOrEqual(10);
expect(value).toBeCloseTo(5.5, 1);

// Strings
expect(string).toMatch(/pattern/);
expect(string).toContain('substring');

// Arrays/Objects
expect(array).toHaveLength(3);
expect(object).toHaveProperty('key', 'value');

// Exceptions
expect(() => fn()).toThrow();
expect(() => fn()).toThrow('error message');
await expect(asyncFn()).rejects.toThrow();
```

## Soft Assertions

Continue test execution after failure, report all failures at end.

```typescript
test('check multiple elements', async ({ page }) => {
	await page.goto('/dashboard');

	// Won't stop on first failure
	await expect.soft(page.getByRole('heading')).toHaveText('Dashboard');
	await expect.soft(page.getByRole('button', { name: 'Save' })).toBeEnabled();
	await expect.soft(page.getByText('Welcome')).toBeVisible();

	// Test continues; all failures reported at end
});
```

### Soft Assertions with Early Exit

```typescript
test('check form', async ({ page }) => {
	await expect.soft(page.getByRole('form')).toBeVisible();

	// Exit early if form not visible (pointless to check fields)
	if (expect.soft.hasFailures()) {
		return;
	}

	await expect.soft(page.getByLabel('Name')).toBeVisible();
	await expect.soft(page.getByLabel('Email')).toBeVisible();
});
```

## Waiting Strategies

### Auto-Waiting (Default)

Actions automatically wait for:

- Element to be attached to DOM
- Element to be visible
- Element to be stable (no animations)
- Element to be enabled
- Element to receive events

```typescript
// These auto-wait
await page.click('button');
await page.fill('input', 'text');
await page.getByRole('button').click();
```

### Wait for Navigation

```typescript
// Wait for URL change
await page.waitForURL('/dashboard');
await page.waitForURL(/\/dashboard/);

// Wait for navigation after action
await Promise.all([page.waitForURL('**/dashboard'), page.click('a[href="/dashboard"]')]);

// Or without Promise.all
const urlPromise = page.waitForURL('**/dashboard');
await page.click('a');
await urlPromise;
```

### Wait for Network

```typescript
// Wait for specific response
const responsePromise = page.waitForResponse('**/api/users');
await page.click('button');
const response = await responsePromise;
expect(response.status()).toBe(200);

// Wait for request
const requestPromise = page.waitForRequest('**/api/submit');
await page.click('button');
const request = await requestPromise;

// Wait for no network activity
await page.waitForLoadState('networkidle');
```

### Wait for Element State

```typescript
// Wait for element to appear
await page.getByRole('dialog').waitFor({ state: 'visible' });

// Wait for element to disappear
await page.getByText('Loading...').waitFor({ state: 'hidden' });

// Wait for element to be attached
await page.getByTestId('result').waitFor({ state: 'attached' });

// Wait for element to be detached
await page.getByTestId('modal').waitFor({ state: 'detached' });
```

### Wait for Function

```typescript
// Wait for arbitrary condition
await page.waitForFunction(() => {
	return document.querySelector('.loaded') !== null;
});

// With arguments
await page.waitForFunction((selector) => document.querySelector(selector)?.textContent === 'Ready', '.status');
```

## Polling & Retrying

### toPass() for Polling

Retry until block passes or times out:

```typescript
await expect(async () => {
	const response = await page.request.get('/api/status');
	expect(response.status()).toBe(200);

	const data = await response.json();
	expect(data.ready).toBe(true);
}).toPass({
	intervals: [1000, 2000, 5000], // Retry intervals
	timeout: 30000
});
```

### expect.poll()

Poll a function until assertion passes:

```typescript
// Poll API until condition met
await expect
	.poll(
		async () => {
			const response = await page.request.get('/api/job/123');
			return (await response.json()).status;
		},
		{
			intervals: [1000, 2000, 5000],
			timeout: 30000
		}
	)
	.toBe('completed');

// Poll DOM value
await expect.poll(() => page.getByTestId('counter').textContent()).toBe('10');
```

## Custom Matchers

```typescript
// playwright.config.ts or fixtures
import { expect } from '@playwright/test';

expect.extend({
	async toHaveDataLoaded(page: Page) {
		const locator = page.getByTestId('data-container');
		let pass = false;
		let message = '';

		try {
			await expect(locator).toBeVisible();
			await expect(locator).not.toContainText('Loading');
			pass = true;
		} catch (e) {
			message = `Expected data to be loaded but found loading state`;
		}

		return { pass, message: () => message };
	}
});

// Extend TypeScript types
declare global {
	namespace PlaywrightTest {
		interface Matchers<R> {
			toHaveDataLoaded(): Promise<R>;
		}
	}
}

// Usage
await expect(page).toHaveDataLoaded();
```

## Timeouts

### Configure Timeouts

```typescript
// playwright.config.ts
export default defineConfig({
	timeout: 30000, // Test timeout
	expect: {
		timeout: 5000 // Assertion timeout
	}
});

// Per-test timeout
test('long test', async ({ page }) => {
	test.setTimeout(60000);
	// ...
});

// Per-assertion timeout
await expect(page.getByRole('button')).toBeVisible({ timeout: 10000 });
```

## Best Practices

| Do                             | Don't                          |
| ------------------------------ | ------------------------------ |
| Use web-first assertions       | Use generic assertions for DOM |
| Let auto-waiting work          | Add unnecessary explicit waits |
| Use `toPass()` for polling     | Write manual retry loops       |
| Configure appropriate timeouts | Use `waitForTimeout()`         |
| Check specific conditions      | Wait for arbitrary time        |

## Anti-Patterns to Avoid

| Anti-Pattern                                              | Problem                       | Solution                                     |
| --------------------------------------------------------- | ----------------------------- | -------------------------------------------- |
| `await page.waitForTimeout(5000)`                         | Slow, flaky, arbitrary timing | Use auto-waiting or `waitForResponse`        |
| `await new Promise(resolve => setTimeout(resolve, 1000))` | Same as above                 | Use `waitForResponse` or element state waits |
| Generic assertions on DOM elements                        | No auto-retry, flaky          | Use web-first assertions with `expect()`     |

## Related References

- **Debugging timeout issues**: See [debugging.md](../debugging/debugging.md) for troubleshooting
- **Fixing flaky tests**: See [debugging.md](../debugging/debugging.md) for race condition solutions
- **Network interception**: See [test-suite-structure.md](test-suite-structure.md) for API mocking
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