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/clock-mocking.md

View on GitHub
# Date, Time & Clock Mocking

## Table of Contents

1. [Clock API Basics](#clock-api-basics)
2. [Fixed Time Testing](#fixed-time-testing)
3. [Time Advancement](#time-advancement)
4. [Timezone Testing](#timezone-testing)
5. [Timer Mocking](#timer-mocking)

## Clock API Basics

### Install Clock

```typescript
test('mock current time', async ({ page }) => {
	// Install clock before navigating
	await page.clock.install({ time: new Date('2025-01-15T09:00:00') });

	await page.goto('/dashboard');

	// Page sees January 15, 2025 as current date
	await expect(page.getByText('January 15, 2025')).toBeVisible();
});
```

### Clock with Fixture

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

type ClockFixtures = {
	mockTime: (date: Date | string) => Promise<void>;
};

export const test = base.extend<ClockFixtures>({
	mockTime: async ({ page }, use) => {
		await use(async (date) => {
			const time = typeof date === 'string' ? new Date(date) : date;
			await page.clock.install({ time });
		});
	}
});

// Usage
test('subscription expiry', async ({ page, mockTime }) => {
	await mockTime('2025-12-31T23:59:00');
	await page.goto('/subscription');

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

## Fixed Time Testing

### Test Date-Dependent Features

```typescript
test('show holiday banner in December', async ({ page }) => {
	await page.clock.install({ time: new Date('2025-12-20T10:00:00') });

	await page.goto('/');

	await expect(page.getByRole('banner', { name: /holiday/i })).toBeVisible();
});

test('no holiday banner in January', async ({ page }) => {
	await page.clock.install({ time: new Date('2025-01-15T10:00:00') });

	await page.goto('/');

	await expect(page.getByRole('banner', { name: /holiday/i })).toBeHidden();
});
```

### Test Relative Time Display

```typescript
test('shows relative time correctly', async ({ page }) => {
	// Fix time to control "posted 2 hours ago" text
	await page.clock.install({ time: new Date('2025-06-15T14:00:00') });

	// Mock API to return post with known timestamp
	await page.route('**/api/posts/1', (route) =>
		route.fulfill({
			json: {
				id: 1,
				title: 'Test Post',
				createdAt: '2025-06-15T12:00:00Z' // 2 hours before mock time
			}
		})
	);

	await page.goto('/posts/1');

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

### Test Date Boundaries

```typescript
test.describe('end of month billing', () => {
	test('shows billing on last day of month', async ({ page }) => {
		await page.clock.install({ time: new Date('2025-01-31T10:00:00') });
		await page.goto('/billing');

		await expect(page.getByText('Payment due today')).toBeVisible();
	});

	test('shows days remaining mid-month', async ({ page }) => {
		await page.clock.install({ time: new Date('2025-01-15T10:00:00') });
		await page.goto('/billing');

		await expect(page.getByText('16 days until payment')).toBeVisible();
	});
});
```

## Time Advancement

### Advance Time Manually

```typescript
test('session timeout warning', async ({ page }) => {
	await page.clock.install({ time: new Date('2025-01-15T09:00:00') });
	await page.goto('/dashboard');

	// Advance 25 minutes (session timeout at 30 min)
	await page.clock.fastForward('25:00');

	await expect(page.getByText('Session expires in 5 minutes')).toBeVisible();

	// Advance 5 more minutes
	await page.clock.fastForward('05:00');

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

### Pause and Resume Time

```typescript
test('countdown timer', async ({ page }) => {
	await page.clock.install({ time: new Date('2025-01-15T09:00:00') });
	await page.goto('/sale');

	// Initial state
	await expect(page.getByText('Sale ends in 2:00:00')).toBeVisible();

	// Advance 1 hour
	await page.clock.fastForward('01:00:00');

	await expect(page.getByText('Sale ends in 1:00:00')).toBeVisible();

	// Advance past end
	await page.clock.fastForward('01:00:01');

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

### Run Pending Timers

```typescript
test('debounced search', async ({ page }) => {
	await page.clock.install({ time: new Date('2025-01-15T09:00:00') });
	await page.goto('/search');

	await page.getByLabel('Search').fill('playwright');

	// Search is debounced by 300ms, won't fire yet
	await expect(page.getByTestId('search-results')).toBeHidden();

	// Fast forward past debounce
	await page.clock.fastForward(300);

	// Now search should execute
	await expect(page.getByTestId('search-results')).toBeVisible();
});
```

## Timezone Testing

### Test Different Timezones

```typescript
test.describe('timezone display', () => {
	test('shows correct time in PST', async ({ browser }) => {
		const context = await browser.newContext({
			timezoneId: 'America/Los_Angeles'
		});
		const page = await context.newPage();

		await page.clock.install({ time: new Date('2025-01-15T17:00:00Z') }); // 5 PM UTC

		await page.goto('/schedule');

		// Should show 9 AM PST
		await expect(page.getByText('9:00 AM')).toBeVisible();

		await context.close();
	});

	test('shows correct time in JST', async ({ browser }) => {
		const context = await browser.newContext({
			timezoneId: 'Asia/Tokyo'
		});
		const page = await context.newPage();

		await page.clock.install({ time: new Date('2025-01-15T17:00:00Z') }); // 5 PM UTC

		await page.goto('/schedule');

		// Should show 2 AM next day JST
		await expect(page.getByText('2:00 AM')).toBeVisible();

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

### Timezone Fixture

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

type TimezoneFixtures = {
	pageInTimezone: (timezone: string) => Promise<Page>;
};

export const test = base.extend<TimezoneFixtures>({
	pageInTimezone: async ({ browser }, use) => {
		const pages: Page[] = [];

		await use(async (timezone) => {
			const context = await browser.newContext({ timezoneId: timezone });
			const page = await context.newPage();
			pages.push(page);
			return page;
		});

		// Cleanup
		for (const page of pages) {
			await page.context().close();
		}
	}
});
```

## Timer Mocking

### Mock setInterval

```typescript
test('auto-refresh data', async ({ page }) => {
	await page.clock.install({ time: new Date('2025-01-15T09:00:00') });

	let apiCalls = 0;
	await page.route('**/api/data', (route) => {
		apiCalls++;
		route.fulfill({ json: { value: apiCalls } });
	});

	await page.goto('/live-data'); // Sets up 30s refresh interval

	expect(apiCalls).toBe(1); // Initial load

	// Advance 30 seconds
	await page.clock.fastForward('00:30');
	expect(apiCalls).toBe(2); // First refresh

	// Advance another 30 seconds
	await page.clock.fastForward('00:30');
	expect(apiCalls).toBe(3); // Second refresh
});
```

### Mock setTimeout Chains

```typescript
test('notification queue', async ({ page }) => {
	await page.clock.install({ time: new Date('2025-01-15T09:00:00') });
	await page.goto('/notifications');

	// Trigger 3 notifications that show sequentially
	await page.getByRole('button', { name: 'Show All' }).click();

	// First notification appears immediately
	await expect(page.getByText('Notification 1')).toBeVisible();

	// Second appears after 2 seconds
	await page.clock.fastForward('00:02');
	await expect(page.getByText('Notification 2')).toBeVisible();

	// Third appears after 2 more seconds
	await page.clock.fastForward('00:02');
	await expect(page.getByText('Notification 3')).toBeVisible();
});
```

### Test Animation Frames

```typescript
test('animation completes', async ({ page }) => {
	await page.clock.install({ time: new Date('2025-01-15T09:00:00') });
	await page.goto('/animation-demo');

	await page.getByRole('button', { name: 'Animate' }).click();

	// Animation runs for 500ms
	const element = page.getByTestId('animated-box');
	await expect(element).toHaveCSS('opacity', '0');

	// Fast forward through animation
	await page.clock.fastForward(500);

	await expect(element).toHaveCSS('opacity', '1');
});
```

## Best Practices

### Always Install Clock Before Navigation

```typescript
// Good
test('date test', async ({ page }) => {
	await page.clock.install({ time: new Date('2025-01-15') });
	await page.goto('/'); // Page loads with mocked time
});

// Bad - time already captured by page
test('date test', async ({ page }) => {
	await page.goto('/');
	await page.clock.install({ time: new Date('2025-01-15') }); // Too late!
});
```

### Use ISO Strings for Clarity

```typescript
// Good - explicit timezone
await page.clock.install({ time: new Date('2025-01-15T09:00:00Z') });

// Ambiguous - uses local timezone
await page.clock.install({ time: new Date('2025-01-15T09:00:00') });
```

## Anti-Patterns to Avoid

| Anti-Pattern                             | Problem                         | Solution                               |
| ---------------------------------------- | ------------------------------- | -------------------------------------- |
| Installing clock after navigation        | Page already captured real time | Install clock before `goto()`          |
| Hardcoded relative dates                 | Tests break over time           | Use fixed dates with clock mock        |
| Not accounting for timezone              | Tests fail in different regions | Use explicit UTC times or set timezone |
| Using `waitForTimeout` with mocked clock | Conflicts with mocked timers    | Use `fastForward` instead              |

## Related References

- **Assertions**: See [assertions-waiting.md](../core/assertions-waiting.md) for time-based assertions
- **Fixtures**: See [fixtures-hooks.md](../core/fixtures-hooks.md) for clock fixtures
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