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/multi-context.md

View on GitHub
# Multi-Tab, Window & Popup Testing

This file covers **single-user scenarios** with multiple browser tabs, windows, and popups. For **multi-user collaboration testing** (multiple users interacting simultaneously), see [multi-user.md](multi-user.md).

## Table of Contents

1. [Popup Handling](#popup-handling)
2. [New Tab Navigation](#new-tab-navigation)
3. [OAuth Flows](#oauth-flows)
4. [Multiple Windows](#multiple-windows)
5. [Tab Coordination](#tab-coordination)

## Popup Handling

### Basic Popup

```typescript
test('handle popup window', async ({ page }) => {
	await page.goto('/');

	// Start waiting for popup before triggering it
	const popupPromise = page.waitForEvent('popup');
	await page.getByRole('button', { name: 'Open Support Chat' }).click();
	const popup = await popupPromise;

	// Wait for popup to load
	await popup.waitForLoadState();

	// Interact with popup
	await popup.getByLabel('Message').fill('Need help');
	await popup.getByRole('button', { name: 'Send' }).click();

	await expect(popup.getByText('Message sent')).toBeVisible();

	// Close popup
	await popup.close();
});
```

### Popup with Authentication

```typescript
test('popup login flow', async ({ page }) => {
	await page.goto('/dashboard');

	const popupPromise = page.waitForEvent('popup');
	await page.getByRole('button', { name: 'Connect Account' }).click();
	const popup = await popupPromise;

	await popup.waitForLoadState();

	// Complete login in popup
	await popup.getByLabel('Email').fill('user@example.com');
	await popup.getByLabel('Password').fill('password123');
	await popup.getByRole('button', { name: 'Log In' }).click();

	// Popup should close automatically after auth
	await popup.waitForEvent('close');

	// Main page should reflect connected state
	await expect(page.getByText('Account connected')).toBeVisible();
});
```

### Handle Blocked Popups

```typescript
test('handle popup blocker', async ({ page }) => {
	await page.goto('/share');

	// Listen for console messages about blocked popup
	page.on('console', (msg) => {
		if (msg.text().includes('popup blocked')) {
			console.log('Popup was blocked');
		}
	});

	const popupPromise = page.waitForEvent('popup').catch(() => null);
	await page.getByRole('button', { name: 'Share to Twitter' }).click();
	const popup = await popupPromise;

	if (!popup) {
		// Popup blocked - app should show fallback
		await expect(page.getByText('Copy share link instead')).toBeVisible();
	}
});
```

## New Tab Navigation

### Link Opens in New Tab

```typescript
test('external link opens in new tab', async ({ page, context }) => {
	await page.goto('/resources');

	// Wait for new page in context
	const pagePromise = context.waitForEvent('page');
	await page.getByRole('link', { name: 'Documentation' }).click();
	const newPage = await pagePromise;

	await newPage.waitForLoadState();

	expect(newPage.url()).toContain('docs.example.com');
	await expect(newPage.getByRole('heading', { level: 1 })).toBeVisible();

	// Original page still there
	expect(page.url()).toContain('/resources');

	await newPage.close();
});
```

### Intercept New Tab

```typescript
test('prevent new tab for testing', async ({ page }) => {
	await page.goto('/links');

	// Remove target="_blank" to keep navigation in same tab
	await page.evaluate(() => {
		document.querySelectorAll('a[target="_blank"]').forEach((a) => {
			a.removeAttribute('target');
		});
	});

	// Now link opens in same tab
	await page.getByRole('link', { name: 'External Site' }).click();

	// Can test the destination page
	await expect(page).toHaveURL(/external-site\.com/);
});
```

## OAuth Flows

### Google OAuth Popup

```typescript
test('Google OAuth login', async ({ page }) => {
	await page.goto('/login');

	const popupPromise = page.waitForEvent('popup');
	await page.getByRole('button', { name: 'Sign in with Google' }).click();
	const popup = await popupPromise;

	await popup.waitForLoadState();

	// Handle Google's OAuth flow
	await popup.getByLabel('Email or phone').fill('test@gmail.com');
	await popup.getByRole('button', { name: 'Next' }).click();

	await popup.getByLabel('Enter your password').fill('password');
	await popup.getByRole('button', { name: 'Next' }).click();

	// Wait for redirect back and popup close
	await popup.waitForEvent('close');

	// Verify logged in on main page
	await expect(page.getByText('Welcome, Test User')).toBeVisible();
});
```

### Mock OAuth (Recommended)

```typescript
test('mock OAuth flow', async ({ page, context }) => {
	// Mock the OAuth callback instead of real flow
	await page.route('**/auth/callback**', async (route) => {
		// Simulate successful OAuth
		const url = new URL(route.request().url());
		url.searchParams.set('code', 'mock-auth-code');
		await route.fulfill({
			status: 302,
			headers: { Location: '/dashboard' }
		});
	});

	// Mock token exchange
	await page.route('**/api/auth/token', (route) =>
		route.fulfill({
			json: {
				access_token: 'mock-token',
				user: { name: 'Test User', email: 'test@example.com' }
			}
		})
	);

	await page.goto('/login');
	await page.getByRole('button', { name: 'Sign in with Google' }).click();

	// Should redirect to dashboard without actual OAuth
	await expect(page).toHaveURL('/dashboard');
	await expect(page.getByText('Welcome, Test User')).toBeVisible();
});
```

### OAuth Fixture

> **For comprehensive OAuth mocking patterns** (fixtures, multiple providers, SAML SSO), see [third-party.md](third-party.md#oauthsso-mocking). This section focuses on popup window handling mechanics for OAuth flows.

## Multiple Windows

### Test Across Multiple Windows

```typescript
test('sync between windows', async ({ context }) => {
	// Open two pages
	const page1 = await context.newPage();
	const page2 = await context.newPage();

	await page1.goto('/dashboard');
	await page2.goto('/dashboard');

	// Make change in first window
	await page1.getByRole('button', { name: 'Add Item' }).click();
	await page1.getByLabel('Name').fill('New Item');
	await page1.getByRole('button', { name: 'Save' }).click();

	// Should sync to second window (if app supports real-time sync)
	await expect(page2.getByText('New Item')).toBeVisible({ timeout: 10000 });
});
```

### Different Users in Different Windows

> **For multi-user collaboration patterns** (admin/user interactions, real-time collaboration, role-based testing, concurrent actions), see [multi-user.md](multi-user.md). This file focuses on single-user scenarios with multiple tabs/windows/popups.

## Tab Coordination

### Switch Between Tabs

```typescript
test('manage multiple tabs', async ({ context }) => {
	const page1 = await context.newPage();
	await page1.goto('/editor');

	const page2 = await context.newPage();
	await page2.goto('/preview');

	// Edit in first tab
	await page1.bringToFront();
	await page1.getByLabel('Content').fill('Hello World');

	// Check preview in second tab
	await page2.bringToFront();
	await page2.reload(); // If preview needs refresh
	await expect(page2.getByText('Hello World')).toBeVisible();
});
```

### Close All Tabs Except One

```typescript
test('cleanup tabs after test', async ({ context }) => {
	const mainPage = await context.newPage();
	await mainPage.goto('/');

	// Open several popups during test
	for (let i = 0; i < 3; i++) {
		const popup = await context.newPage();
		await popup.goto(`/popup/${i}`);
	}

	// Close all except main page
	for (const page of context.pages()) {
		if (page !== mainPage) {
			await page.close();
		}
	}

	expect(context.pages()).toHaveLength(1);
});
```

## Anti-Patterns to Avoid

| Anti-Pattern            | Problem                        | Solution                                   |
| ----------------------- | ------------------------------ | ------------------------------------------ |
| Not waiting for popup   | Race condition                 | Use `waitForEvent("popup")` before trigger |
| Testing real OAuth      | Slow, flaky, needs credentials | Mock OAuth endpoints                       |
| Assuming popup opens    | May be blocked                 | Handle both open and blocked cases         |
| Not closing extra pages | Resource leak                  | Close pages in cleanup                     |

## Related References

- **Authentication**: See [fixtures-hooks.md](../core/fixtures-hooks.md) for auth patterns
- **Network**: See [network-advanced.md](network-advanced.md) for mocking OAuth
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