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/mobile-testing.md

View on GitHub
# Mobile & Responsive Testing

## Table of Contents

1. [Device Emulation](#device-emulation)
2. [Touch Gestures](#touch-gestures)
3. [Viewport Testing](#viewport-testing)
4. [Mobile-Specific UI](#mobile-specific-ui)
5. [Responsive Breakpoints](#responsive-breakpoints)

## Device Emulation

### Use Built-in Devices

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

// Configure in playwright.config.ts
export default defineConfig({
	projects: [
		{ name: 'Desktop Chrome', use: { ...devices['Desktop Chrome'] } },
		{ name: 'Mobile Safari', use: { ...devices['iPhone 14'] } },
		{ name: 'Mobile Chrome', use: { ...devices['Pixel 7'] } },
		{ name: 'Tablet', use: { ...devices['iPad Pro 11'] } }
	]
});
```

### Custom Device Configuration

```typescript
test.use({
	viewport: { width: 390, height: 844 },
	deviceScaleFactor: 3,
	isMobile: true,
	hasTouch: true,
	userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15'
});

test('custom mobile device', async ({ page }) => {
	await page.goto('/');
	// Test runs with custom device settings
});
```

### Test Across Multiple Devices

```typescript
const mobileDevices = ['iPhone 14', 'Pixel 7', 'Galaxy S21'];

for (const deviceName of mobileDevices) {
	test(`checkout on ${deviceName}`, async ({ browser }) => {
		const device = devices[deviceName];
		const context = await browser.newContext({ ...device });
		const page = await context.newPage();

		await page.goto('/checkout');
		await expect(page.getByRole('button', { name: 'Pay' })).toBeVisible();

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

## Touch Gestures

### Tap

```typescript
test.use({ hasTouch: true });

test('tap to interact', async ({ page }) => {
	await page.goto('/gallery');

	// Tap is like click but for touch devices
	await page.getByRole('img', { name: 'Photo 1' }).tap();

	await expect(page.getByRole('dialog')).toBeVisible();
});
```

### Swipe

```typescript
test('swipe carousel', async ({ page }) => {
	await page.goto('/carousel');

	const carousel = page.getByTestId('carousel');
	const box = await carousel.boundingBox();

	if (box) {
		// Swipe left
		await page.touchscreen.tap(box.x + box.width - 50, box.y + box.height / 2);
		await page.mouse.move(box.x + 50, box.y + box.height / 2);

		// Or use drag
		await carousel.dragTo(carousel, {
			sourcePosition: { x: box.width - 50, y: box.height / 2 },
			targetPosition: { x: 50, y: box.height / 2 }
		});
	}

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

### Swipe Fixture

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

type TouchFixtures = {
	swipe: (element: Locator, direction: 'left' | 'right' | 'up' | 'down') => Promise<void>;
};

export const test = base.extend<TouchFixtures>({
	swipe: async ({ page }, use) => {
		await use(async (element, direction) => {
			const box = await element.boundingBox();
			if (!box) throw new Error('Element not visible');

			const centerX = box.x + box.width / 2;
			const centerY = box.y + box.height / 2;
			const distance = 100;

			const moves = {
				left: {
					startX: centerX + distance,
					endX: centerX - distance,
					y: centerY
				},
				right: {
					startX: centerX - distance,
					endX: centerX + distance,
					y: centerY
				},
				up: {
					startX: centerX,
					endX: centerX,
					startY: centerY + distance,
					endY: centerY - distance
				},
				down: {
					startX: centerX,
					endX: centerX,
					startY: centerY - distance,
					endY: centerY + distance
				}
			};

			const move = moves[direction];
			await page.touchscreen.tap(move.startX, move.startY ?? move.y);
			await page.mouse.move(move.endX, move.endY ?? move.y, { steps: 10 });
			await page.mouse.up();
		});
	}
});

// Usage
test('swipe to delete', async ({ page, swipe }) => {
	await page.goto('/inbox');

	const message = page.getByTestId('message-1');
	await swipe(message, 'left');

	await expect(page.getByRole('button', { name: 'Delete' })).toBeVisible();
});
```

### Long Press

```typescript
test('long press for context menu', async ({ page }) => {
	await page.goto('/files');

	const file = page.getByText('document.pdf');
	const box = await file.boundingBox();

	if (box) {
		// Touch down
		await page.touchscreen.tap(box.x + box.width / 2, box.y + box.height / 2);

		// Hold for 500ms
		await page.waitForTimeout(500);

		// Context menu should appear
		await expect(page.getByRole('menu')).toBeVisible();
	}
});
```

### Pinch Zoom

```typescript
test('pinch to zoom image', async ({ page }) => {
	await page.goto('/map');

	// Pinch zoom requires two touch points
	// Playwright doesn't have native pinch support, so we simulate via evaluate
	await page.evaluate(() => {
		const element = document.querySelector('#map');
		if (element) {
			// Simulate wheel event as fallback for zoom
			element.dispatchEvent(
				new WheelEvent('wheel', {
					deltaY: -100, // Negative = zoom in
					ctrlKey: true // Ctrl+wheel = pinch on many apps
				})
			);
		}
	});

	// Or trigger the app's zoom function directly
	await page.evaluate(() => {
		(window as any).mapInstance?.setZoom(15);
	});
});
```

## Viewport Testing

### Test Different Sizes

```typescript
const viewports = [
	{ name: 'mobile', width: 375, height: 667 },
	{ name: 'tablet', width: 768, height: 1024 },
	{ name: 'desktop', width: 1920, height: 1080 }
];

for (const { name, width, height } of viewports) {
	test(`navigation on ${name}`, async ({ page }) => {
		await page.setViewportSize({ width, height });
		await page.goto('/');

		if (width < 768) {
			// Mobile: should have hamburger menu
			await expect(page.getByRole('button', { name: 'Menu' })).toBeVisible();
		} else {
			// Desktop: should have visible nav links
			await expect(page.getByRole('link', { name: 'Products' })).toBeVisible();
		}
	});
}
```

### Dynamic Viewport Changes

```typescript
test('responsive layout change', async ({ page }) => {
	await page.setViewportSize({ width: 1200, height: 800 });
	await page.goto('/dashboard');

	// Desktop: sidebar visible
	await expect(page.getByRole('complementary')).toBeVisible();

	// Resize to mobile
	await page.setViewportSize({ width: 375, height: 667 });

	// Mobile: sidebar hidden, hamburger visible
	await expect(page.getByRole('complementary')).toBeHidden();
	await expect(page.getByRole('button', { name: 'Menu' })).toBeVisible();
});
```

## Mobile-Specific UI

### Hamburger Menu

```typescript
test('mobile navigation', async ({ page }) => {
	await page.setViewportSize({ width: 375, height: 667 });
	await page.goto('/');

	// Open hamburger menu
	await page.getByRole('button', { name: 'Menu' }).click();

	// Navigation drawer should appear
	const nav = page.getByRole('navigation');
	await expect(nav).toBeVisible();

	// Navigate via mobile menu
	await nav.getByRole('link', { name: 'Products' }).click();

	await expect(page).toHaveURL('/products');
	// Menu should close after navigation
	await expect(nav).toBeHidden();
});
```

### Bottom Sheet

```typescript
test('bottom sheet interaction', async ({ page }) => {
	await page.setViewportSize({ width: 375, height: 667 });
	await page.goto('/product/123');

	await page.getByRole('button', { name: 'Add to Cart' }).click();

	// Bottom sheet appears
	const sheet = page.getByRole('dialog');
	await expect(sheet).toBeVisible();

	// Select options
	await sheet.getByRole('combobox', { name: 'Size' }).selectOption('Large');
	await sheet.getByRole('button', { name: 'Confirm' }).click();

	await expect(page.getByText('Added to cart')).toBeVisible();
});
```

### Pull to Refresh

```typescript
test('pull to refresh', async ({ page }) => {
	await page.goto('/feed');

	const feed = page.getByTestId('feed');
	const initialFirstItem = await feed.locator('> *').first().textContent();

	// Simulate pull down
	const box = await feed.boundingBox();
	if (box) {
		await page.touchscreen.tap(box.x + box.width / 2, box.y + 50);
		await page.mouse.move(box.x + box.width / 2, box.y + 200, { steps: 20 });
		await page.mouse.up();
	}

	// Wait for refresh
	await expect(page.getByTestId('loading')).toBeVisible();
	await expect(page.getByTestId('loading')).toBeHidden();

	// Content should be updated (in a real app)
});
```

## Responsive Breakpoints

### Test All Breakpoints

```typescript
const breakpoints = {
	xs: 320,
	sm: 640,
	md: 768,
	lg: 1024,
	xl: 1280,
	'2xl': 1536
};

test.describe('responsive header', () => {
	for (const [name, width] of Object.entries(breakpoints)) {
		test(`header at ${name} (${width}px)`, async ({ page }) => {
			await page.setViewportSize({ width, height: 800 });
			await page.goto('/');

			if (width < 768) {
				await expect(page.getByTestId('mobile-menu-button')).toBeVisible();
				await expect(page.getByTestId('desktop-nav')).toBeHidden();
			} else {
				await expect(page.getByTestId('mobile-menu-button')).toBeHidden();
				await expect(page.getByTestId('desktop-nav')).toBeVisible();
			}
		});
	}
});
```

### Visual Regression at Breakpoints

```typescript
test.describe('visual regression', () => {
	const sizes = [
		{ width: 375, height: 667, name: 'mobile' },
		{ width: 768, height: 1024, name: 'tablet' },
		{ width: 1440, height: 900, name: 'desktop' }
	];

	for (const { width, height, name } of sizes) {
		test(`homepage at ${name}`, async ({ page }) => {
			await page.setViewportSize({ width, height });
			await page.goto('/');

			await expect(page).toHaveScreenshot(`homepage-${name}.png`);
		});
	}
});
```

## Anti-Patterns to Avoid

| Anti-Pattern                | Problem                   | Solution                         |
| --------------------------- | ------------------------- | -------------------------------- |
| Only testing one viewport   | Misses responsive bugs    | Test multiple breakpoints        |
| Ignoring touch events       | Features broken on mobile | Test tap, swipe, long press      |
| Hardcoded viewport in tests | Can't test multiple sizes | Use `page.setViewportSize()`     |
| Not testing orientation     | Landscape bugs missed     | Test both portrait and landscape |

## Related References

- **Visual Testing**: See [test-suite-structure.md](../core/test-suite-structure.md) for screenshot testing
- **Locators**: See [locators.md](../core/locators.md) for mobile-friendly selectors
- **Browser APIs**: See [browser-apis.md](../browser-apis/browser-apis.md) for permissions (camera, geolocation, notifications)
- **Canvas/Touch**: See [canvas-webgl.md](../testing-patterns/canvas-webgl.md) for touch gestures on canvas elements
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