13 / 74 · 10 Visual & Accessibility Testing · Open-Source Visual Regression Tools← prev⊞ allnext →☰ Read as one page
3.2Playwright Built-in Visual Testing
Playwright includes screenshot comparison out of the box with no additional dependencies. This is the recommended starting point for most teams.
// tests/visual/playwright-native.spec.ts
import { test, expect } from '@playwright/test';
test('login page matches baseline', async ({ page }) => {
await page.goto('/login');
// Full page screenshot comparison
await expect(page).toHaveScreenshot('login-page.png', {
fullPage: true,
maxDiffPixelRatio: 0.01, // Allow 1% pixel difference
threshold: 0.2, // Per-pixel color threshold (0-1)
animations: 'disabled', // Freeze animations for consistency
});
});
test('navigation component matches baseline', async ({ page }) => {
await page.goto('/');
// Component-level screenshot
const nav = page.locator('nav[data-testid="main-nav"]');
await expect(nav).toHaveScreenshot('main-navigation.png', {
maxDiffPixelRatio: 0.005,
});
});
test('modal dialog matches baseline', async ({ page }) => {
await page.goto('/');
await page.click('[data-testid="open-modal"]');
// Mask dynamic content before capturing
await expect(page).toHaveScreenshot('confirmation-modal.png', {
mask: [
page.locator('[data-testid="timestamp"]'),
page.locator('[data-testid="user-avatar"]'),
page.locator('[data-testid="order-id"]'),
],
});
});
Playwright Screenshot Configuration
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
expect: {
toHaveScreenshot: {
// Default comparison settings
maxDiffPixelRatio: 0.01,
threshold: 0.2,
animations: 'disabled',
},
},
// Store baselines in a dedicated directory
snapshotPathTemplate: '{testDir}/__screenshots__/{testFilePath}/{arg}{ext}',
});
Updating Baselines
# Update all baselines (after intentional changes)
npx playwright test --update-snapshots
# Update baselines for specific tests
npx playwright test tests/visual/homepage.spec.ts --update-snapshots
# Review changes in a side-by-side report
npx playwright show-report
Handling Cross-Platform Differences
Playwright screenshots differ across operating systems due to font rendering. Handle this with platform-specific baselines:
// Playwright automatically stores OS-specific baselines:
// __screenshots__/login-page-chromium-linux.png
// __screenshots__/login-page-chromium-darwin.png
// __screenshots__/login-page-chromium-win32.png
// Or use a Docker container for consistent rendering:
// docker run --rm -v $(pwd):/work mcr.microsoft.com/playwright:v1.61.0-noble \
// npx playwright test --update-snapshots