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

testing-patterns/i18n.md

View on GitHub
# Internationalization (i18n) Testing

## Table of Contents

1. [Locale Configuration](#locale-configuration)
2. [Testing Multiple Locales](#testing-multiple-locales)
3. [RTL Layout Testing](#rtl-layout-testing)
4. [Date, Time & Number Formats](#date-time--number-formats)
5. [Translation Verification](#translation-verification)
6. [Visual Regression for i18n](#visual-regression-for-i18n)

## Locale Configuration

### Setting Browser Locale

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

export default defineConfig({
	projects: [
		{
			name: 'english',
			use: {
				...devices['Desktop Chrome'],
				locale: 'en-US',
				timezoneId: 'America/New_York'
			}
		},
		{
			name: 'german',
			use: {
				...devices['Desktop Chrome'],
				locale: 'de-DE',
				timezoneId: 'Europe/Berlin'
			}
		},
		{
			name: 'japanese',
			use: {
				...devices['Desktop Chrome'],
				locale: 'ja-JP',
				timezoneId: 'Asia/Tokyo'
			}
		},
		{
			name: 'arabic',
			use: {
				...devices['Desktop Chrome'],
				locale: 'ar-SA',
				timezoneId: 'Asia/Riyadh'
			}
		}
	]
});
```

### Per-Test Locale Override

```typescript
test('test in French locale', async ({ browser }) => {
	const context = await browser.newContext({
		locale: 'fr-FR',
		timezoneId: 'Europe/Paris'
	});

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

	// Verify French content
	await expect(page.getByRole('button', { name: 'Connexion' })).toBeVisible();

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

### Accept-Language Header

```typescript
test('server-side locale detection', async ({ browser }) => {
	const context = await browser.newContext({
		locale: 'es-ES',
		extraHTTPHeaders: {
			'Accept-Language': 'es-ES,es;q=0.9,en;q=0.8'
		}
	});

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

	// Server should respond with Spanish content
	await expect(page.locator('html')).toHaveAttribute('lang', 'es');
});
```

## Testing Multiple Locales

### Parameterized Locale Tests

```typescript
const locales = [
	{ locale: 'en-US', greeting: 'Hello', button: 'Sign In' },
	{ locale: 'de-DE', greeting: 'Hallo', button: 'Anmelden' },
	{ locale: 'fr-FR', greeting: 'Bonjour', button: 'Se connecter' },
	{ locale: 'ja-JP', greeting: 'こんにちは', button: 'ログイン' }
];

for (const { locale, greeting, button } of locales) {
	test(`login page in ${locale}`, async ({ browser }) => {
		const context = await browser.newContext({ locale });
		const page = await context.newPage();

		await page.goto('/login');

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

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

### Locale Fixture

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

type LocaleFixtures = {
	localePage: (locale: string) => Promise<Page>;
};

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

		const createLocalePage = async (locale: string) => {
			const context = await browser.newContext({ locale });
			const page = await context.newPage();
			pages.push(page);
			return page;
		};

		await use(createLocalePage);

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

// Usage
test('compare locales', async ({ localePage }) => {
	const enPage = await localePage('en-US');
	const dePage = await localePage('de-DE');

	await enPage.goto('/pricing');
	await dePage.goto('/pricing');

	const enPrice = await enPage.getByTestId('price').textContent();
	const dePrice = await dePage.getByTestId('price').textContent();

	expect(enPrice).toContain('$');
	expect(dePrice).toContain('€');
});
```

### Testing Locale Switching

```typescript
test('user can switch locale', async ({ page }) => {
	await page.goto('/');

	// Initial locale (from browser)
	await expect(page.locator('html')).toHaveAttribute('lang', 'en');

	// Switch to German
	await page.getByRole('button', { name: 'Language' }).click();
	await page.getByRole('menuitem', { name: 'Deutsch' }).click();

	// Verify switch
	await expect(page.locator('html')).toHaveAttribute('lang', 'de');
	await expect(page.getByRole('heading', { level: 1 })).toContainText(/Willkommen/);

	// Verify persistence (reload)
	await page.reload();
	await expect(page.locator('html')).toHaveAttribute('lang', 'de');
});
```

## RTL Layout Testing

### Setting Up RTL Tests

```typescript
// playwright.config.ts
export default defineConfig({
	projects: [
		{
			name: 'rtl-arabic',
			use: {
				locale: 'ar-SA'
				// RTL is usually set by the app based on locale
			}
		},
		{
			name: 'rtl-hebrew',
			use: {
				locale: 'he-IL'
			}
		}
	]
});
```

### Verifying RTL Direction

```typescript
test('RTL layout is applied', async ({ page }) => {
	await page.goto('/');

	// Check document direction
	await expect(page.locator('html')).toHaveAttribute('dir', 'rtl');

	// Or check computed style
	const direction = await page.evaluate(() => {
		return window.getComputedStyle(document.body).direction;
	});
	expect(direction).toBe('rtl');
});
```

### RTL-Specific Element Positioning

```typescript
test('sidebar is on the right in RTL', async ({ page }) => {
	await page.goto('/dashboard');

	const sidebar = page.getByTestId('sidebar');
	const main = page.getByTestId('main-content');

	const sidebarBox = await sidebar.boundingBox();
	const mainBox = await main.boundingBox();

	// In RTL, sidebar should be to the right of main content
	expect(sidebarBox!.x).toBeGreaterThan(mainBox!.x);
});
```

### RTL Visual Regression

```typescript
test('RTL layout matches snapshot', async ({ page }) => {
	await page.goto('/');

	// Screenshot for RTL comparison
	await expect(page).toHaveScreenshot('homepage-rtl.png', {
		// Separate snapshots per locale/direction
		fullPage: true
	});
});

// LTR comparison
test('LTR layout matches snapshot', async ({ browser }) => {
	const context = await browser.newContext({ locale: 'en-US' });
	const page = await context.newPage();

	await page.goto('/');
	await expect(page).toHaveScreenshot('homepage-ltr.png', { fullPage: true });
});
```

### Testing Bidirectional Text

```typescript
test('bidirectional text renders correctly', async ({ page }) => {
	await page.goto('/profile');

	// Mixed LTR/RTL content
	const nameField = page.getByTestId('full-name');

	// Arabic name with English email
	await expect(nameField).toContainText('محمد (mohammed@example.com)');

	// Verify text doesn't overlap or break
	const box = await nameField.boundingBox();
	expect(box!.width).toBeGreaterThan(100); // Content not collapsed
});
```

## Date, Time & Number Formats

### Testing Date Formats

```typescript
test('dates are formatted per locale', async ({ browser }) => {
	const testDate = new Date('2024-03-15');

	const formats = [
		{ locale: 'en-US', expected: 'March 15, 2024' },
		{ locale: 'en-GB', expected: '15 March 2024' },
		{ locale: 'de-DE', expected: '15. März 2024' },
		{ locale: 'ja-JP', expected: '2024年3月15日' }
	];

	for (const { locale, expected } of formats) {
		const context = await browser.newContext({ locale });
		const page = await context.newPage();

		await page.goto(`/event?date=${testDate.toISOString()}`);

		const dateDisplay = page.getByTestId('event-date');
		await expect(dateDisplay).toContainText(expected);

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

### Testing Number Formats

```typescript
test('numbers are formatted per locale', async ({ browser }) => {
	const testNumber = 1234567.89;

	const formats = [
		{ locale: 'en-US', expected: '1,234,567.89' },
		{ locale: 'de-DE', expected: '1.234.567,89' },
		{ locale: 'fr-FR', expected: '1 234 567,89' }
	];

	for (const { locale, expected } of formats) {
		const context = await browser.newContext({ locale });
		const page = await context.newPage();

		await page.goto(`/stats?value=${testNumber}`);

		await expect(page.getByTestId('formatted-number')).toHaveText(expected);

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

### Testing Currency Formats

```typescript
test('currency displays correctly', async ({ browser }) => {
	const price = 99.99;

	const currencies = [
		{ locale: 'en-US', currency: 'USD', expected: '$99.99' },
		{ locale: 'de-DE', currency: 'EUR', expected: '99,99 €' },
		{ locale: 'ja-JP', currency: 'JPY', expected: '¥100' }, // JPY has no decimals
		{ locale: 'en-GB', currency: 'GBP', expected: '£99.99' }
	];

	for (const { locale, currency, expected } of currencies) {
		const context = await browser.newContext({ locale });
		const page = await context.newPage();

		await page.goto(`/product?price=${price}&currency=${currency}`);

		await expect(page.getByTestId('price')).toContainText(expected);

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

## Translation Verification

### Checking for Missing Translations

```typescript
test('no missing translations', async ({ page }) => {
	await page.goto('/');

	// Common patterns for missing translations
	const missingPatterns = [
		/\{\{.*\}\}/, // Handlebars-style
		/\$\{.*\}/, // Template literal style
		/t\(["'][\w.]+["']\)/, // i18n key exposed
		/MISSING_TRANSLATION/, // Common placeholder
		/\[UNTRANSLATED\]/ // Another placeholder
	];

	const bodyText = await page.locator('body').textContent();

	for (const pattern of missingPatterns) {
		expect(bodyText).not.toMatch(pattern);
	}
});
```

### Detecting Text Overflow

```typescript
test('translations fit UI containers', async ({ browser }) => {
	const locales = ['en-US', 'de-DE', 'fr-FR', 'es-ES'];
	const issues: string[] = [];

	for (const locale of locales) {
		const context = await browser.newContext({ locale });
		const page = await context.newPage();
		await page.goto('/');

		const overflowing = await page.evaluate(() => {
			const elements = document.querySelectorAll('button, .label, h1, h2, h3');
			return Array.from(elements)
				.filter((el) => (el as HTMLElement).scrollWidth > (el as HTMLElement).clientWidth)
				.map((el) => `${el.tagName}: "${el.textContent?.substring(0, 20)}..."`);
		});

		if (overflowing.length > 0) issues.push(`${locale}: ${overflowing.join(', ')}`);
		await context.close();
	}

	expect(issues).toEqual([]);
});
```

## Visual Regression for i18n

### Locale-Specific Snapshots

```typescript
// playwright.config.ts
export default defineConfig({
	snapshotPathTemplate: '{testDir}/__snapshots__/{projectName}/{testFilePath}/{arg}{ext}',

	projects: [
		{ name: 'en-US', use: { locale: 'en-US' } },
		{ name: 'de-DE', use: { locale: 'de-DE' } },
		{ name: 'ja-JP', use: { locale: 'ja-JP' } },
		{ name: 'ar-SA', use: { locale: 'ar-SA' } }
	]
});
```

```typescript
// test file
test('homepage visual', async ({ page }) => {
	await page.goto('/');

	// Snapshot auto-saved to {projectName}/homepage.png
	await expect(page).toHaveScreenshot('homepage.png');
});
```

### Critical Element Screenshots

```typescript
test('navigation in all locales', async ({ page }) => {
	await page.goto('/');

	// Just the nav - catches overflow, truncation
	const nav = page.getByRole('navigation');
	await expect(nav).toHaveScreenshot('navigation.png');
});

test('buttons dont truncate', async ({ page }) => {
	await page.goto('/checkout');

	const ctaButton = page.getByRole('button', {
		name: /checkout|kaufen|acheter/i
	});
	await expect(ctaButton).toHaveScreenshot('checkout-button.png');
});
```

### Font Loading for i18n

```typescript
test('wait for fonts before screenshot', async ({ page }) => {
	await page.goto('/');

	// Wait for fonts (important for CJK, Arabic)
	await page.evaluate(() => document.fonts.ready);
	await page.waitForFunction(() => document.fonts.check("16px 'Noto Sans Arabic'"));

	await expect(page).toHaveScreenshot('with-fonts.png');
});
```

## Anti-Patterns to Avoid

| Anti-Pattern              | Problem                         | Solution                        |
| ------------------------- | ------------------------------- | ------------------------------- |
| Hardcoded text assertions | Breaks in other locales         | Use test IDs or parameterize    |
| Single locale testing     | Misses i18n bugs                | Test multiple locales           |
| Ignoring RTL              | Layout broken for RTL users     | Dedicated RTL project           |
| No font wait              | Screenshots with fallback fonts | Wait for `document.fonts.ready` |

## Related References

- **Clock Mocking**: See [clock-mocking.md](../advanced/clock-mocking.md) for timezone testing
- **Mobile Testing**: See [mobile-testing.md](../advanced/mobile-testing.md) for device-specific locales
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