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

advanced/network-advanced.md

View on GitHub
# Advanced Network Interception

## Table of Contents

1. [Request Modification](#request-modification)
2. [GraphQL Mocking](#graphql-mocking)
3. [HAR Recording & Playback](#har-recording--playback)
4. [Conditional Mocking](#conditional-mocking)
5. [Network Throttling](#network-throttling)

## Request Modification

### Modify Request Headers

```typescript
test('add auth header to requests', async ({ page }) => {
	await page.route('**/api/**', (route) => {
		const headers = {
			...route.request().headers(),
			Authorization: 'Bearer test-token',
			'X-Test-Header': 'test-value'
		};
		route.continue({ headers });
	});

	await page.goto('/dashboard');
});
```

### Modify Request Body

```typescript
test('modify POST body', async ({ page }) => {
	await page.route('**/api/orders', async (route) => {
		if (route.request().method() === 'POST') {
			const postData = route.request().postDataJSON();

			// Add test metadata
			const modifiedData = {
				...postData,
				testMode: true,
				testTimestamp: Date.now()
			};

			await route.continue({
				postData: JSON.stringify(modifiedData)
			});
		} else {
			await route.continue();
		}
	});

	await page.goto('/checkout');
	await page.getByRole('button', { name: 'Place Order' }).click();
});
```

### Transform Response

```typescript
test('modify API response', async ({ page }) => {
	await page.route('**/api/products', async (route) => {
		// Fetch real response
		const response = await route.fetch();
		const json = await response.json();

		// Modify response
		const modified = json.map((product: any) => ({
			...product,
			price: product.price * 0.9, // 10% discount
			testMode: true
		}));

		await route.fulfill({
			response,
			json: modified
		});
	});

	await page.goto('/products');
});
```

## GraphQL Mocking

### Mock by Operation Name

```typescript
test('mock GraphQL query', async ({ page }) => {
	await page.route('**/graphql', async (route) => {
		const postData = route.request().postDataJSON();

		if (postData.operationName === 'GetUser') {
			return route.fulfill({
				json: {
					data: {
						user: {
							id: '1',
							name: 'Test User',
							email: 'test@example.com'
						}
					}
				}
			});
		}

		if (postData.operationName === 'GetProducts') {
			return route.fulfill({
				json: {
					data: {
						products: [
							{ id: '1', name: 'Product A', price: 29.99 },
							{ id: '2', name: 'Product B', price: 49.99 }
						]
					}
				}
			});
		}

		// Pass through unmocked operations
		return route.continue();
	});

	await page.goto('/dashboard');
});
```

### GraphQL Mock Fixture

```typescript
// fixtures/graphql.fixture.ts
type GraphQLMock = {
	operation: string;
	variables?: Record<string, any>;
	response: { data?: any; errors?: any[] };
};

type GraphQLFixtures = {
	mockGraphQL: (mocks: GraphQLMock[]) => Promise<void>;
};

export const test = base.extend<GraphQLFixtures>({
	mockGraphQL: async ({ page }, use) => {
		await use(async (mocks) => {
			await page.route('**/graphql', async (route) => {
				const postData = route.request().postDataJSON();

				const mock = mocks.find((m) => {
					if (m.operation !== postData.operationName) return false;

					// Optionally match variables
					if (m.variables) {
						return JSON.stringify(m.variables) === JSON.stringify(postData.variables);
					}
					return true;
				});

				if (mock) {
					return route.fulfill({ json: mock.response });
				}

				return route.continue();
			});
		});
	}
});

// Usage
test('dashboard with mocked GraphQL', async ({ page, mockGraphQL }) => {
	await mockGraphQL([
		{
			operation: 'GetDashboardStats',
			response: {
				data: { stats: { users: 100, revenue: 50000 } }
			}
		},
		{
			operation: 'GetUser',
			variables: { id: '1' },
			response: {
				data: { user: { id: '1', name: 'John' } }
			}
		}
	]);

	await page.goto('/dashboard');
	await expect(page.getByText('100 users')).toBeVisible();
});
```

### Mock GraphQL Mutations

```typescript
test('mock GraphQL mutation', async ({ page }) => {
	await page.route('**/graphql', async (route) => {
		const postData = route.request().postDataJSON();

		if (postData.operationName === 'CreateOrder') {
			const { input } = postData.variables;

			return route.fulfill({
				json: {
					data: {
						createOrder: {
							id: 'order-123',
							status: 'PENDING',
							items: input.items,
							total: input.items.reduce((sum: number, item: any) => sum + item.price * item.quantity, 0)
						}
					}
				}
			});
		}

		return route.continue();
	});

	await page.goto('/checkout');
	await page.getByRole('button', { name: 'Place Order' }).click();

	await expect(page.getByText('Order #order-123')).toBeVisible();
});
```

## HAR Recording & Playback

### Record HAR File

```typescript
// Record network traffic
test('record HAR', async ({ page, context }) => {
	// Start recording
	await context.routeFromHAR('./recordings/checkout.har', {
		update: true, // Create/update HAR file
		url: '**/api/**'
	});

	await page.goto('/checkout');
	await page.getByRole('button', { name: 'Place Order' }).click();

	// HAR file is saved automatically
});
```

### Playback HAR File

```typescript
// Use recorded HAR for offline testing
test('playback HAR', async ({ page, context }) => {
	await context.routeFromHAR('./recordings/checkout.har', {
		url: '**/api/**',
		update: false // Don't update, just playback
	});

	await page.goto('/checkout');

	// All API calls served from HAR file
	await expect(page.getByText('Order confirmed')).toBeVisible();
});
```

### HAR with Fallback

```typescript
test('HAR with live fallback', async ({ page, context }) => {
	await context.routeFromHAR('./recordings/api.har', {
		url: '**/api/**',
		update: false,
		notFound: 'fallback' // Use real network if not in HAR
	});

	await page.goto('/dashboard');
});
```

## Conditional Mocking

### Mock Based on Request Body

```typescript
test('conditional mock by body', async ({ page }) => {
	await page.route('**/api/search', async (route) => {
		const body = route.request().postDataJSON();

		if (body.query === 'error') {
			return route.fulfill({
				status: 500,
				json: { error: 'Search failed' }
			});
		}

		if (body.query === 'empty') {
			return route.fulfill({
				json: { results: [] }
			});
		}

		// Default response
		return route.fulfill({
			json: {
				results: [{ id: 1, title: `Result for: ${body.query}` }]
			}
		});
	});

	await page.goto('/search');

	// Test different scenarios
	await page.getByLabel('Search').fill('error');
	await page.getByLabel('Search').press('Enter');
	await expect(page.getByText('Search failed')).toBeVisible();
});
```

### Mock Nth Request

```typescript
test('different response on retry', async ({ page }) => {
	let callCount = 0;

	await page.route('**/api/status', (route) => {
		callCount++;

		if (callCount < 3) {
			return route.fulfill({
				status: 503,
				json: { error: 'Service unavailable' }
			});
		}

		// Succeed on 3rd attempt
		return route.fulfill({
			json: { status: 'ok' }
		});
	});

	await page.goto('/dashboard');

	// App should retry and eventually succeed
	await expect(page.getByText('Connected')).toBeVisible();
});
```

### Mock with Delay

```typescript
test('slow network simulation', async ({ page }) => {
	await page.route('**/api/data', async (route) => {
		// Simulate 2 second delay
		await new Promise((resolve) => setTimeout(resolve, 2000));

		return route.fulfill({
			json: { data: 'loaded' }
		});
	});

	await page.goto('/dashboard');

	// Loading state should appear
	await expect(page.getByText('Loading...')).toBeVisible();

	// Then data appears
	await expect(page.getByText('loaded')).toBeVisible();
});
```

## Network Throttling

### Slow 3G Simulation

```typescript
test('slow network experience', async ({ page, context }) => {
	// Create CDP session for network throttling
	const client = await context.newCDPSession(page);

	await client.send('Network.emulateNetworkConditions', {
		offline: false,
		downloadThroughput: (500 * 1024) / 8, // 500 Kbps
		uploadThroughput: (500 * 1024) / 8,
		latency: 400 // 400ms
	});

	await page.goto('/');

	// Test loading states appear
	await expect(page.getByTestId('skeleton-loader')).toBeVisible();
});
```

### Offline Mode

Use `context.setOffline(true/false)` to simulate network connectivity changes.

> **For comprehensive offline testing patterns:**
>
> - **Network failure simulation** (error recovery, graceful degradation): See [error-testing.md](error-testing.md#offline-testing)
> - **Offline-first/PWA testing** (service workers, caching, background sync): See [service-workers.md](service-workers.md#offline-testing)

### Network Throttling Fixture

```typescript
// fixtures/network.fixture.ts
type NetworkCondition = 'slow3g' | 'fast3g' | 'offline';

const conditions = {
	slow3g: { downloadThroughput: 50000, uploadThroughput: 50000, latency: 2000 },
	fast3g: { downloadThroughput: 180000, uploadThroughput: 75000, latency: 150 }
};

type NetworkFixtures = {
	setNetworkCondition: (condition: NetworkCondition) => Promise<void>;
};

export const test = base.extend<NetworkFixtures>({
	setNetworkCondition: async ({ page, context }, use) => {
		const client = await context.newCDPSession(page);

		await use(async (condition) => {
			if (condition === 'offline') {
				await context.setOffline(true);
			} else {
				await client.send('Network.emulateNetworkConditions', {
					offline: false,
					...conditions[condition]
				});
			}
		});

		// Reset
		await context.setOffline(false);
	}
});
```

## Anti-Patterns to Avoid

| Anti-Pattern             | Problem                        | Solution                         |
| ------------------------ | ------------------------------ | -------------------------------- |
| Mocking all requests     | Tests don't reflect reality    | Mock only what's necessary       |
| No cleanup of routes     | Routes persist across tests    | Use fixtures with cleanup        |
| Ignoring request method  | Mock applies to wrong requests | Check `route.request().method()` |
| Hardcoded mock responses | Brittle, hard to maintain      | Use factories for mock data      |

## Related References

- **Basic Mocking**: See [test-suite-structure.md](../core/test-suite-structure.md) for simple mocking
- **WebSockets**: See [websockets.md](../browser-apis/websockets.md) for real-time 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