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

browser-apis/websockets.md

View on GitHub
# WebSocket & Real-Time Testing

## Table of Contents

1. [WebSocket Basics](#websocket-basics)
2. [Mocking WebSocket Messages](#mocking-websocket-messages)
3. [Testing Real-Time Features](#testing-real-time-features)
4. [Server-Sent Events](#server-sent-events)
5. [Reconnection Testing](#reconnection-testing)

## WebSocket Basics

### Wait for WebSocket Connection

```typescript
test('chat connects via websocket', async ({ page }) => {
	// Listen for WebSocket connection
	const wsPromise = page.waitForEvent('websocket');

	await page.goto('/chat');

	const ws = await wsPromise;
	expect(ws.url()).toContain('/ws/chat');

	// Wait for connection to be established
	await ws.waitForEvent('framesent');
});
```

### Monitor WebSocket Messages

```typescript
test('receives real-time updates', async ({ page }) => {
	const messages: string[] = [];

	// Set up listener before navigation
	page.on('websocket', (ws) => {
		ws.on('framereceived', (frame) => {
			messages.push(frame.payload as string);
		});
	});

	await page.goto('/dashboard');

	// Wait for some messages
	await expect.poll(() => messages.length).toBeGreaterThan(0);

	// Verify message format
	const data = JSON.parse(messages[0]);
	expect(data).toHaveProperty('type');
});
```

### Capture Sent Messages

```typescript
test('sends correct message format', async ({ page }) => {
	const sentMessages: string[] = [];

	page.on('websocket', (ws) => {
		ws.on('framesent', (frame) => {
			sentMessages.push(frame.payload as string);
		});
	});

	await page.goto('/chat');
	await page.getByLabel('Message').fill('Hello!');
	await page.getByRole('button', { name: 'Send' }).click();

	// Verify sent message
	await expect.poll(() => sentMessages.length).toBeGreaterThan(0);

	const sent = JSON.parse(sentMessages[sentMessages.length - 1]);
	expect(sent).toEqual({
		type: 'message',
		content: 'Hello!'
	});
});
```

## Mocking WebSocket Messages

### Inject Messages via Page Evaluate

```typescript
test('displays incoming chat message', async ({ page }) => {
	await page.goto('/chat');

	// Wait for WebSocket to be ready
	await page.waitForFunction(() => (window as any).chatSocket?.readyState === 1);

	// Simulate incoming message
	await page.evaluate(() => {
		const event = new MessageEvent('message', {
			data: JSON.stringify({
				type: 'message',
				from: 'Alice',
				content: 'Hello there!'
			})
		});
		(window as any).chatSocket.dispatchEvent(event);
	});

	await expect(page.getByText('Alice: Hello there!')).toBeVisible();
});
```

### Mock WebSocket with Route Handler

```typescript
test('mock websocket entirely', async ({ page, context }) => {
	// Intercept the WebSocket upgrade
	await context.route('**/ws/**', async (route) => {
		// For WebSocket routes, we can't fulfill directly
		// Instead, use page.evaluate to mock the client-side
	});

	// Alternative: Mock at application level
	await page.addInitScript(() => {
		const OriginalWebSocket = window.WebSocket;
		(window as any).WebSocket = function (url: string) {
			const ws = {
				readyState: 1,
				send: (data: string) => {
					console.log('WS Send:', data);
				},
				close: () => {},
				addEventListener: () => {},
				removeEventListener: () => {}
			};
			setTimeout(() => ws.onopen?.(), 100);
			return ws;
		};
	});

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

### WebSocket Mock Fixture

```typescript
// fixtures/websocket.fixture.ts
import { test as base, Page } from '@playwright/test';

type WsMessage = { type: string; [key: string]: any };

type WebSocketFixtures = {
	mockWebSocket: {
		injectMessage: (message: WsMessage) => Promise<void>;
		getSentMessages: () => Promise<WsMessage[]>;
	};
};

export const test = base.extend<WebSocketFixtures>({
	mockWebSocket: async ({ page }, use) => {
		const sentMessages: WsMessage[] = [];

		// Capture sent messages
		await page.addInitScript(() => {
			(window as any).__wsSent = [];
			const OriginalWebSocket = window.WebSocket;
			window.WebSocket = function (url: string) {
				const ws = new OriginalWebSocket(url);
				const originalSend = ws.send.bind(ws);
				ws.send = (data: string) => {
					(window as any).__wsSent.push(JSON.parse(data));
					originalSend(data);
				};
				(window as any).__ws = ws;
				return ws;
			} as any;
		});

		await use({
			injectMessage: async (message) => {
				await page.evaluate((msg) => {
					const event = new MessageEvent('message', {
						data: JSON.stringify(msg)
					});
					(window as any).__ws?.dispatchEvent(event);
				}, message);
			},
			getSentMessages: async () => {
				return page.evaluate(() => (window as any).__wsSent || []);
			}
		});
	}
});

// Usage
test('chat with mocked websocket', async ({ page, mockWebSocket }) => {
	await page.goto('/chat');

	// Inject incoming message
	await mockWebSocket.injectMessage({
		type: 'message',
		from: 'Bob',
		content: 'Hi!'
	});

	await expect(page.getByText('Bob: Hi!')).toBeVisible();

	// Send a reply
	await page.getByLabel('Message').fill('Hello Bob!');
	await page.getByRole('button', { name: 'Send' }).click();

	// Verify sent message
	const sent = await mockWebSocket.getSentMessages();
	expect(sent).toContainEqual(expect.objectContaining({ content: 'Hello Bob!' }));
});
```

## Testing Real-Time Features

### Live Notifications

```typescript
test('displays live notification', async ({ page }) => {
	await page.goto('/dashboard');

	// Simulate notification via WebSocket
	await page.evaluate(() => {
		const event = new MessageEvent('message', {
			data: JSON.stringify({
				type: 'notification',
				title: 'New Order',
				message: 'Order #123 received'
			})
		});
		(window as any).notificationSocket.dispatchEvent(event);
	});

	await expect(page.getByRole('alert')).toContainText('Order #123 received');
});
```

### Live Data Updates

```typescript
test('updates stock price in real-time', async ({ page }) => {
	await page.goto('/stocks/AAPL');

	const priceElement = page.getByTestId('stock-price');
	const initialPrice = await priceElement.textContent();

	// Simulate price update
	await page.evaluate(() => {
		const event = new MessageEvent('message', {
			data: JSON.stringify({
				type: 'price_update',
				symbol: 'AAPL',
				price: 150.25
			})
		});
		(window as any).stockSocket.dispatchEvent(event);
	});

	await expect(priceElement).not.toHaveText(initialPrice!);
	await expect(priceElement).toContainText('150.25');
});
```

### Collaborative Editing

```typescript
test('shows collaborator cursor', async ({ page }) => {
	await page.goto('/document/123');

	// Simulate another user's cursor position
	await page.evaluate(() => {
		const event = new MessageEvent('message', {
			data: JSON.stringify({
				type: 'cursor',
				userId: 'user-456',
				userName: 'Alice',
				position: { x: 100, y: 200 }
			})
		});
		(window as any).docSocket.dispatchEvent(event);
	});

	await expect(page.getByTestId('cursor-user-456')).toBeVisible();
	await expect(page.getByText('Alice')).toBeVisible();
});
```

## Server-Sent Events

### Test SSE Updates

```typescript
test('receives SSE updates', async ({ page }) => {
	// Mock SSE endpoint
	await page.route('**/api/events', (route) => {
		route.fulfill({
			status: 200,
			headers: {
				'Content-Type': 'text/event-stream',
				'Cache-Control': 'no-cache',
				Connection: 'keep-alive'
			},
			body: `data: {"type":"update","value":42}\n\n`
		});
	});

	await page.goto('/live-data');

	await expect(page.getByTestId('value')).toHaveText('42');
});
```

### Simulate Multiple SSE Events

```typescript
test('handles multiple SSE events', async ({ page }) => {
	await page.route('**/api/events', async (route) => {
		const encoder = new TextEncoder();
		const events = [`data: {"count":1}\n\n`, `data: {"count":2}\n\n`, `data: {"count":3}\n\n`];

		route.fulfill({
			status: 200,
			headers: { 'Content-Type': 'text/event-stream' },
			body: events.join('')
		});
	});

	await page.goto('/counter');

	// Should receive all events
	await expect(page.getByTestId('count')).toHaveText('3');
});
```

## Reconnection Testing

### Test Connection Loss

```typescript
test('handles connection loss gracefully', async ({ page }) => {
	await page.goto('/chat');

	// Simulate connection close
	await page.evaluate(() => {
		(window as any).chatSocket.close();
	});

	// Should show disconnected state
	await expect(page.getByText('Reconnecting...')).toBeVisible();
});
```

### Test Reconnection

```typescript
test('reconnects after connection loss', async ({ page }) => {
	await page.goto('/chat');

	// Simulate disconnect
	await page.evaluate(() => {
		(window as any).chatSocket.close();
	});

	await expect(page.getByText('Reconnecting...')).toBeVisible();

	// Simulate reconnection
	await page.evaluate(() => {
		const event = new Event('open');
		(window as any).chatSocket = { readyState: 1 };
		(window as any).chatSocket.dispatchEvent?.(event);
	});

	// Force component to re-check connection
	await page.evaluate(() => {
		window.dispatchEvent(new Event('online'));
	});

	await expect(page.getByText('Connected')).toBeVisible();
});
```

## Anti-Patterns to Avoid

| Anti-Pattern                          | Problem                       | Solution                           |
| ------------------------------------- | ----------------------------- | ---------------------------------- |
| Not waiting for WebSocket ready       | Messages sent too early       | Wait for `readyState === 1`        |
| Testing against real WebSocket server | Flaky, timing-dependent       | Mock WebSocket messages            |
| Ignoring connection state             | Tests pass but feature broken | Test connected/disconnected states |
| No cleanup of listeners               | Memory leaks in tests         | Clean up event listeners           |

## Related References

- **Network**: See [network-advanced.md](../advanced/network-advanced.md) for HTTP mocking patterns
- **Assertions**: See [assertions-waiting.md](../core/assertions-waiting.md) for polling patterns
- **Multi-User**: See [multi-user.md](../advanced/multi-user.md) for real-time collaboration testing with multiple users
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