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

frameworks/nextjs.md

View on GitHub
# Next.js Testing Patterns

## Table of Contents

1. [Setup](#setup)
2. [App Router Patterns](#app-router-patterns)
3. [Pages Router Patterns](#pages-router-patterns)
4. [Dynamic Routes](#dynamic-routes)
5. [API Routes](#api-routes)
6. [Middleware Testing](#middleware-testing)
7. [Hydration Testing](#hydration-testing)
8. [next/image Testing](#nextimage-testing)
9. [NextAuth.js Authentication](#nextauthjs-authentication)
10. [Tips](#tips)
11. [Anti-Patterns](#anti-patterns)
12. [Related](#related)

> **When to use**: Testing Next.js applications with App Router, Pages Router, API routes, middleware, SSR, dynamic routes, and server components.
> **Prerequisites**: [configuration.md](../core/configuration.md), [locators.md](../core/locators.md)

## Setup

### Configuration with webServer

```typescript
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
	testDir: './tests',
	fullyParallel: true,
	forbidOnly: !!process.env.CI,
	retries: process.env.CI ? 2 : 0,
	workers: process.env.CI ? '50%' : undefined,

	use: {
		baseURL: 'http://localhost:3000',
		trace: 'on-first-retry',
		screenshot: 'only-on-failure'
	},

	projects: [
		{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
		{ name: 'mobile', use: { ...devices['iPhone 14'] } }
	],

	webServer: {
		command: process.env.CI ? 'npm run build && npm run start' : 'npm run dev',
		url: 'http://localhost:3000',
		reuseExistingServer: !process.env.CI,
		timeout: 120_000,
		env: {
			NODE_ENV: process.env.CI ? 'production' : 'test'
		}
	}
});
```

### Environment Variables

Next.js loads `.env.test` when `NODE_ENV=test`:

```bash
# .env.test (commit this)
NEXT_PUBLIC_API_URL=http://localhost:3000/api
DATABASE_URL=postgresql://localhost:5432/test_db

# .env.test.local (gitignored)
NEXTAUTH_SECRET=test-secret-local
```

## App Router Patterns

### Server Component Content

```typescript
test('renders server component content', async ({ page }) => {
	await page.goto('/');

	await expect(page.getByRole('heading', { name: 'Welcome', level: 1 })).toBeVisible();
	await expect(page.getByRole('navigation', { name: 'Main' })).toBeVisible();
});
```

### Loading States with Streaming

```typescript
test('loading state during data streaming', async ({ page }) => {
	await page.route('**/api/stats', async (route) => {
		await new Promise((r) => setTimeout(r, 2000));
		await route.continue();
	});

	await page.goto('/dashboard');

	await expect(page.getByRole('progressbar')).toBeVisible();
	await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
	await expect(page.getByRole('progressbar')).toBeHidden();
});
```

### Nested Layouts

```typescript
test('layouts persist across navigation', async ({ page }) => {
	await page.goto('/dashboard/analytics');

	const sidebar = page.getByRole('navigation', { name: 'Dashboard' });
	await expect(sidebar).toBeVisible();

	await sidebar.getByRole('link', { name: 'Settings' }).click();
	await page.waitForURL('/dashboard/settings');

	await expect(sidebar).toBeVisible();
	await expect(page.getByRole('heading', { name: 'Settings' })).toBeVisible();
});
```

## Pages Router Patterns

### SSR with getServerSideProps

```typescript
test('page with getServerSideProps renders data', async ({ page }) => {
	await page.goto('/blog');

	await expect(page.getByRole('heading', { name: 'Blog', level: 1 })).toBeVisible();
	await expect(page.getByRole('article')).toHaveCount(10);
	await expect(page.getByRole('article').first()).toContainText(/\w+/);
});
```

### Static Generation with getStaticProps

```typescript
test('static page shows pre-rendered content', async ({ page }) => {
	await page.goto('/about');

	await expect(page.getByRole('heading', { name: 'About Us' })).toBeVisible();
	await expect(page.getByText('Founded in 2020')).toBeVisible();
});
```

## Dynamic Routes

### Slug Parameters

```typescript
test('dynamic [slug] renders correct content', async ({ page }) => {
	await page.goto('/blog/testing-guide');

	await expect(page.getByRole('heading', { level: 1 })).toContainText('Testing Guide');
	await expect(page.getByText('Page not found')).toBeHidden();
});

test('non-existent slug shows 404', async ({ page }) => {
	const response = await page.goto('/blog/nonexistent-post');

	expect(response?.status()).toBe(404);
	await expect(page.getByRole('heading', { name: '404' })).toBeVisible();
});
```

### Catch-All Routes

```typescript
test('catch-all handles nested paths', async ({ page }) => {
	await page.goto('/docs/getting-started/installation');
	await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible();

	await page.goto('/docs/api/configuration');
	await expect(page.getByRole('heading', { name: 'Configuration' })).toBeVisible();
});
```

### Query Parameters

```typescript
test('query parameters filter content', async ({ page }) => {
	await page.goto('/products?category=electronics&sort=price-asc');

	await expect(page.getByRole('heading', { name: 'Electronics' })).toBeVisible();

	const prices = await page.getByTestId('product-price').allTextContents();
	const numericPrices = prices.map((p) => parseFloat(p.replace('$', '')));
	expect(numericPrices).toEqual([...numericPrices].sort((a, b) => a - b));
});
```

## API Routes

### Direct API Testing

```typescript
test('GET /api/products returns list', async ({ request }) => {
	const response = await request.get('/api/products');

	expect(response.ok()).toBeTruthy();
	const body = await response.json();
	expect(body.products).toBeInstanceOf(Array);
	expect(body.products[0]).toHaveProperty('id');
	expect(body.products[0]).toHaveProperty('name');
});

test('POST /api/products creates item', async ({ request }) => {
	const response = await request.post('/api/products', {
		data: { name: 'Test Product', price: 29.99 }
	});

	expect(response.status()).toBe(201);
	const body = await response.json();
	expect(body.product.name).toBe('Test Product');
});

test('POST /api/products validates fields', async ({ request }) => {
	const response = await request.post('/api/products', {
		data: { name: '' }
	});

	expect(response.status()).toBe(400);
	const body = await response.json();
	expect(body.error).toContainEqual(expect.objectContaining({ field: 'price' }));
});
```

### API Through UI

```typescript
test('form submission calls API', async ({ page }) => {
	await page.goto('/products/new');

	await page.getByLabel('Product name').fill('Widget');
	await page.getByLabel('Price').fill('19.99');
	await page.getByRole('button', { name: 'Create product' }).click();

	await expect(page.getByText('Product created successfully')).toBeVisible();
	await page.waitForURL('/products/**');
});
```

## Middleware Testing

### Auth Redirects

```typescript
test('unauthenticated user redirected to login', async ({ page }) => {
	await page.goto('/dashboard');

	expect(page.url()).toContain('/login');
	await expect(page.getByRole('heading', { name: 'Sign in' })).toBeVisible();
});

test('redirect preserves return URL', async ({ page }) => {
	await page.goto('/dashboard/settings');

	const url = new URL(page.url());
	expect(url.pathname).toBe('/login');
	expect(url.searchParams.get('callbackUrl') || url.searchParams.get('returnTo')).toContain('/dashboard/settings');
});
```

### Security Headers

```typescript
test('middleware sets security headers', async ({ page }) => {
	const response = await page.goto('/');

	const headers = response!.headers();
	expect(headers['x-frame-options']).toBe('DENY');
	expect(headers['x-content-type-options']).toBe('nosniff');
});
```

### Locale Rewrites

```typescript
test('middleware rewrites based on locale', async ({ page, context }) => {
	await context.setExtraHTTPHeaders({
		'Accept-Language': 'fr-FR,fr;q=0.9'
	});

	await page.goto('/');

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

## Hydration Testing

### Console Error Detection

```typescript
test('no hydration errors in console', async ({ page }) => {
	const consoleErrors: string[] = [];
	page.on('console', (msg) => {
		if (msg.type() === 'error') {
			consoleErrors.push(msg.text());
		}
	});

	await page.goto('/');
	await page.getByRole('button', { name: 'Get started' }).click();

	const hydrationErrors = consoleErrors.filter(
		(e) => e.includes('Hydration') || e.includes('hydration') || e.includes('did not match')
	);
	expect(hydrationErrors).toEqual([]);
});
```

### Interactive Elements After Hydration

```typescript
test('interactive elements work after hydration', async ({ page }) => {
	await page.goto('/');

	const counter = page.getByTestId('counter-value');
	await expect(counter).toHaveText('0');

	await page.getByRole('button', { name: 'Increment' }).click();
	await expect(counter).toHaveText('1');
});
```

## next/image Testing

```typescript
test('hero image loads with srcset', async ({ page }) => {
	await page.goto('/');

	const heroImage = page.getByRole('img', { name: 'Hero banner' });
	await expect(heroImage).toBeVisible();

	const srcset = await heroImage.getAttribute('srcset');
	expect(srcset).toBeTruthy();
	expect(srcset).toContain('w=');

	const loading = await heroImage.getAttribute('loading');
	expect(loading).not.toBe('lazy');
});

test('offscreen images lazy load', async ({ page }) => {
	await page.goto('/gallery');

	const offscreenImage = page.getByRole('img', { name: 'Gallery item 20' });

	await offscreenImage.scrollIntoViewIfNeeded();
	await expect(offscreenImage).toBeVisible();

	const naturalWidth = await offscreenImage.evaluate((img: HTMLImageElement) => img.naturalWidth);
	expect(naturalWidth).toBeGreaterThan(0);
});
```

## NextAuth.js Authentication

### Setup Project

```typescript
// playwright.config.ts
export default defineConfig({
	projects: [
		{ name: 'setup', testMatch: /auth\.setup\.ts/ },
		{
			name: 'authenticated',
			use: { storageState: 'playwright/.auth/user.json' },
			dependencies: ['setup']
		},
		{ name: 'unauthenticated', testMatch: '**/*.unauth.spec.ts' }
	]
});
```

### Auth Setup

```typescript
// tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';

const authFile = 'playwright/.auth/user.json';

setup('authenticate via credentials', async ({ page }) => {
	await page.goto('/login');
	await page.getByLabel('Email').fill('test@example.com');
	await page.getByLabel('Password').fill(process.env.TEST_PASSWORD!);
	await page.getByRole('button', { name: 'Sign in' }).click();

	await page.waitForURL('/dashboard');
	await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();

	await page.context().storageState({ path: authFile });
});
```

### Authenticated Tests

```typescript
test('authenticated user sees dashboard', async ({ page }) => {
	await page.goto('/dashboard');

	await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
	await expect(page.getByText('test@example.com')).toBeVisible();
});
```

## Tips

### Dev Server vs Production Build

| Scenario          | Command                          | Trade-off                              |
| ----------------- | -------------------------------- | -------------------------------------- |
| Local development | `npm run dev`                    | Fast iteration, no production behavior |
| CI pipeline       | `npm run build && npm run start` | Tests real production bundle           |

### Turbopack

```typescript
webServer: {
  command: process.env.CI
    ? 'npm run build && npm run start'
    : 'npx next dev --turbopack',
  url: 'http://localhost:3000',
  reuseExistingServer: !process.env.CI,
},
```

### Multiple webServer Entries

```typescript
webServer: [
  {
    command: 'npm run dev:api',
    url: 'http://localhost:4000/health',
    reuseExistingServer: !process.env.CI,
  },
  {
    command: 'npm run dev',
    url: 'http://localhost:3000',
    reuseExistingServer: !process.env.CI,
  },
],
```

## Anti-Patterns

| Don't Do This                               | Problem                             | Do This Instead                                                           |
| ------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------- |
| `await page.waitForTimeout(3000)`           | Arbitrary waits are fragile         | `await page.waitForURL('/path')` or `await expect(locator).toBeVisible()` |
| Test `getServerSideProps` directly          | Depends on req/res context          | Navigate to page and verify rendered output                               |
| Mock your own API routes                    | Hides real API bugs                 | Let real API handle requests; mock only external services                 |
| `page.goto('http://localhost:3000/path')`   | Breaks when port changes            | Use `page.goto('/path')` with `baseURL`                                   |
| Run `npm run build` locally for every test  | Extremely slow                      | Use `npm run dev` locally with `reuseExistingServer: true`                |
| Test `next/image` by checking exact URLs    | Paths change between dev/prod       | Assert on `alt`, visibility, `naturalWidth > 0`, `srcset`                 |
| Test server actions by calling as functions | Server actions need Next.js runtime | Trigger through UI (forms, buttons)                                       |

## Related

- [configuration.md](../core/configuration.md) -- Playwright configuration including `webServer`
- [authentication.md](../advanced/authentication.md) -- authentication setup and `storageState`
- [api-testing.md](../testing-patterns/api-testing.md) -- testing API routes with `request` context
- [react.md](react.md) -- React patterns for Next.js client components
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