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

core/global-setup.md

View on GitHub
# Global Setup & Teardown

## Table of Contents

1. [Global Setup](#global-setup)
2. [Global Teardown](#global-teardown)
3. [Database Patterns](#database-patterns)
4. [Environment Provisioning](#environment-provisioning)
5. [Setup Projects vs Global Setup](#setup-projects-vs-global-setup)
6. [Parallel Execution Caveats](#parallel-execution-caveats)

## Global Setup

### Basic Global Setup

```typescript
// global-setup.ts
import { FullConfig } from '@playwright/test';

async function globalSetup(config: FullConfig) {
	console.log('Running global setup...');
	// Perform one-time setup: start services, run migrations, etc.
}

export default globalSetup;
```

### Configure Global Setup

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

export default defineConfig({
	globalSetup: require.resolve('./global-setup'),
	globalTeardown: require.resolve('./global-teardown')
});
```

> **Authentication in Global Setup**: For authentication patterns using storage state in global setup, see [fixtures-hooks.md](fixtures-hooks.md#authentication-patterns). Setup projects are generally preferred for authentication as they provide access to Playwright fixtures.

### Global Setup with Return Value

```typescript
// global-setup.ts
async function globalSetup(config: FullConfig): Promise<() => Promise<void>> {
	const server = await startTestServer();

	// Return cleanup function (alternative to globalTeardown)
	return async () => {
		await server.stop();
	};
}

export default globalSetup;
```

### Access Config in Global Setup

```typescript
// global-setup.ts
import { FullConfig } from '@playwright/test';

async function globalSetup(config: FullConfig) {
	const { baseURL } = config.projects[0].use;
	console.log(`Setting up for ${baseURL}`);

	// Access custom config
	const workers = config.workers;
	const timeout = config.timeout;

	// Access environment
	const isCI = !!process.env.CI;
}

export default globalSetup;
```

## Global Teardown

### Basic Global Teardown

```typescript
// global-teardown.ts
import { FullConfig } from '@playwright/test';
import fs from 'fs';

async function globalTeardown(config: FullConfig) {
	console.log('Running global teardown...');

	// Clean up auth files
	if (fs.existsSync('.auth')) {
		fs.rmSync('.auth', { recursive: true });
	}

	// Clean up test data
	await cleanupTestDatabase();

	// Stop services
	await stopTestServices();
}

export default globalTeardown;
```

### Conditional Teardown

```typescript
// global-teardown.ts
async function globalTeardown(config: FullConfig) {
	// Skip cleanup in CI (containers are discarded anyway)
	if (process.env.CI) {
		console.log('Skipping teardown in CI');
		return;
	}

	// Local cleanup
	await cleanupLocalTestData();
}

export default globalTeardown;
```

## Database Patterns

This section covers **one-time database setup** (migrations, snapshots, per-worker databases). For related topics:

- **Per-test database fixtures** (isolation, transaction rollback): See [fixtures-hooks.md](fixtures-hooks.md#database-fixtures)
- **Test data factories** (builders, Faker): See [test-data.md](test-data.md)

### Database Migration in Setup

```typescript
// global-setup.ts
import { execSync } from 'child_process';

async function globalSetup() {
	console.log('Running database migrations...');

	// Run migrations
	execSync('npx prisma migrate deploy', { stdio: 'inherit' });

	// Seed test data
	execSync('npx prisma db seed', { stdio: 'inherit' });
}

export default globalSetup;
```

### Database Snapshot Pattern

```typescript
// global-setup.ts
import { execSync } from 'child_process';
import fs from 'fs';

const SNAPSHOT_PATH = './test-db-snapshot.sql';

async function globalSetup() {
	// Check if snapshot exists
	if (fs.existsSync(SNAPSHOT_PATH)) {
		console.log('Restoring database from snapshot...');
		execSync(`psql $DATABASE_URL < ${SNAPSHOT_PATH}`, { stdio: 'inherit' });
		return;
	}

	// First run: migrate and create snapshot
	console.log('Creating database snapshot...');
	execSync('npx prisma migrate deploy', { stdio: 'inherit' });
	execSync('npx prisma db seed', { stdio: 'inherit' });
	execSync(`pg_dump $DATABASE_URL > ${SNAPSHOT_PATH}`, { stdio: 'inherit' });
}

export default globalSetup;
```

### Test Database per Worker

```typescript
// global-setup.ts
async function globalSetup(config: FullConfig) {
	const workerCount = config.workers || 1;

	// Create a database for each worker
	for (let i = 0; i < workerCount; i++) {
		const dbName = `test_db_worker_${i}`;
		await createDatabase(dbName);
		await runMigrations(dbName);
		await seedDatabase(dbName);
	}
}

// global-teardown.ts
async function globalTeardown(config: FullConfig) {
	const workerCount = config.workers || 1;

	for (let i = 0; i < workerCount; i++) {
		await dropDatabase(`test_db_worker_${i}`);
	}
}
```

## Environment Provisioning

### Start Services in Setup

```typescript
// global-setup.ts
import { execSync, spawn } from 'child_process';

let serverProcess: any;

async function globalSetup() {
	// Start backend server
	serverProcess = spawn('npm', ['run', 'start:test'], {
		stdio: 'pipe',
		detached: true
	});

	// Wait for server to be ready
	await waitForServer('http://localhost:3000/health', 30000);

	// Store PID for teardown
	process.env.SERVER_PID = serverProcess.pid.toString();
}

async function waitForServer(url: string, timeout: number) {
	const start = Date.now();

	while (Date.now() - start < timeout) {
		try {
			const response = await fetch(url);
			if (response.ok) return;
		} catch {
			// Server not ready yet
		}
		await new Promise((r) => setTimeout(r, 1000));
	}

	throw new Error(`Server did not start within ${timeout}ms`);
}

export default globalSetup;
```

### Docker Compose Setup

```typescript
// global-setup.ts
import { execSync } from 'child_process';

async function globalSetup() {
	console.log('Starting Docker services...');

	execSync('docker-compose -f docker-compose.test.yml up -d', {
		stdio: 'inherit'
	});

	// Wait for services to be healthy
	execSync('docker-compose -f docker-compose.test.yml exec -T db pg_isready', {
		stdio: 'inherit'
	});
}

export default globalSetup;
```

```typescript
// global-teardown.ts
import { execSync } from 'child_process';

async function globalTeardown() {
	console.log('Stopping Docker services...');

	execSync('docker-compose -f docker-compose.test.yml down -v', {
		stdio: 'inherit'
	});
}

export default globalTeardown;
```

### Environment Variables Setup

```typescript
// global-setup.ts
import dotenv from 'dotenv';
import path from 'path';

async function globalSetup() {
	// Load test-specific environment
	const envFile = process.env.CI ? '.env.ci' : '.env.test';
	dotenv.config({ path: path.resolve(process.cwd(), envFile) });

	// Validate required variables
	const required = ['DATABASE_URL', 'API_KEY', 'TEST_EMAIL'];
	for (const key of required) {
		if (!process.env[key]) {
			throw new Error(`Missing required environment variable: ${key}`);
		}
	}
}

export default globalSetup;
```

## Setup Projects vs Global Setup

### When to Use Each

| Use Global Setup                      | Use Setup Projects                       |
| ------------------------------------- | ---------------------------------------- |
| One-time setup (migrations, services) | Per-project setup (auth states)          |
| No access to Playwright fixtures      | Need page, request fixtures              |
| Runs once before all projects         | Can run per-project or have dependencies |
| Shared across all workers             | Can be parallelized                      |

### Setup Project Pattern

```typescript
// playwright.config.ts
export default defineConfig({
	projects: [
		// Setup project
		{
			name: 'setup',
			testMatch: /.*\.setup\.ts/
		},
		// Test projects depend on setup
		{
			name: 'chromium',
			use: { ...devices['Desktop Chrome'] },
			dependencies: ['setup']
		},
		{
			name: 'firefox',
			use: { ...devices['Desktop Firefox'] },
			dependencies: ['setup']
		}
	]
});
```

> **For complete authentication setup patterns**, see [fixtures-hooks.md](fixtures-hooks.md#authentication-patterns).

### Combining Both

```typescript
// playwright.config.ts
export default defineConfig({
	// Global: Start services, run migrations
	globalSetup: require.resolve('./global-setup'),
	globalTeardown: require.resolve('./global-teardown'),

	projects: [
		// Setup project: Create auth states
		{ name: 'setup', testMatch: /.*\.setup\.ts/ },
		{
			name: 'chromium',
			use: {
				...devices['Desktop Chrome'],
				storageState: '.auth/user.json'
			},
			dependencies: ['setup']
		}
	]
});
```

## Parallel Execution Caveats

### Understanding Global Setup Execution

```
┌─────────────────────────────────────────────────────────────┐
│  globalSetup runs ONCE                                      │
│  ↓                                                          │
│  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐        │
│  │ Worker 1│  │ Worker 2│  │ Worker 3│  │ Worker 4│        │
│  │ tests   │  │ tests   │  │ tests   │  │ tests   │        │
│  └─────────┘  └─────────┘  └─────────┘  └─────────┘        │
│  ↓                                                          │
│  globalTeardown runs ONCE                                   │
└─────────────────────────────────────────────────────────────┘
```

**Key implications:**

- Global setup has **no access** to Playwright fixtures (`page`, `request`, `context`)
- State created in global setup is **shared** across all workers
- If tests **modify** shared state, they may conflict with parallel workers
- Global setup **cannot** react to individual test needs

### When to Prefer Worker-Scoped Fixtures

Use **worker-scoped fixtures** instead of globalSetup when:

| Scenario                             | Why Fixtures Are Better                              |
| ------------------------------------ | ---------------------------------------------------- |
| Each worker needs isolated resources | Fixtures can create per-worker databases, servers    |
| Setup needs Playwright APIs          | Fixtures have access to `page`, `request`, `browser` |
| Setup depends on test configuration  | Fixtures receive test context and options            |
| Resources need cleanup per worker    | Worker fixtures auto-cleanup when worker exits       |

### Common Parallel Pitfall

```typescript
// ❌ BAD: Global setup creates ONE user, all workers fight over it
async function globalSetup() {
	await createUser({ email: 'test@example.com' }); // Shared!
}

// ✅ GOOD: Each worker gets its own user via worker-scoped fixture
// Uses workerInfo.workerIndex to create unique data per worker
```

> **For worker-scoped fixture patterns** (per-worker databases, unique test data, `workerIndex` isolation), see [fixtures-hooks.md](fixtures-hooks.md#isolate-test-data-between-parallel-workers).

## Anti-Patterns to Avoid

| Anti-Pattern                   | Problem                          | Solution                                   |
| ------------------------------ | -------------------------------- | ------------------------------------------ |
| Heavy setup in globalSetup     | Slow test startup                | Use setup projects for parallelizable work |
| Not cleaning up in teardown    | Leaks resources, flaky CI        | Always clean up or use containers          |
| Hardcoded URLs in setup        | Breaks in different environments | Use config.projects[0].use.baseURL         |
| No timeout on service wait     | Hangs forever if service fails   | Add timeout with clear error               |
| Shared mutable state           | Race conditions in parallel      | Use worker-scoped fixtures for isolation   |
| Global setup for per-test data | Tests conflict                   | Use test-scoped fixtures                   |

## Related References

- **Fixtures & Auth**: See [fixtures-hooks.md](fixtures-hooks.md) for worker-scoped fixtures and auth patterns
- **CI/CD**: See [ci-cd.md](../infrastructure-ci-cd/ci-cd.md) for CI setup patterns
- **Projects**: See [projects-dependencies.md](projects-dependencies.md) for project configuration
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