patterntypescriptnoneTip
Visual Regression Testing with Playwright Screenshots
Viewed 0 times
visual regressionscreenshot testingPlaywrightpixel diffbaselinetoHaveScreenshot
Error Messages
Problem
CSS changes unintentionally break visual layouts that unit tests don't catch. Manual visual reviews are slow and miss subtle pixel-level regressions.
Solution
Use Playwright's built-in screenshot comparison for visual regression testing.
import { test, expect } from '@playwright/test';
test('homepage visual regression', async ({ page }) => {
await page.goto('/');
// Wait for animations to settle
await page.waitForLoadState('networkidle');
// Full page screenshot comparison
await expect(page).toHaveScreenshot('homepage.png', {
maxDiffPixels: 100, // Allow minor rendering differences
threshold: 0.2, // Per-pixel color tolerance
});
});
test('button states', async ({ page }) => {
await page.goto('/components');
const button = page.getByRole('button', { name: 'Submit' });
// Screenshot specific element
await expect(button).toHaveScreenshot('button-default.png');
await button.hover();
await expect(button).toHaveScreenshot('button-hover.png');
});
// Update snapshots when intentional:
// npx playwright test --update-snapshotsWhy
Playwright's screenshot diffing detects pixel-level visual changes that DOM assertions miss (CSS layout shifts, font rendering, color changes). Baseline images are stored in source control.
Gotchas
- Screenshots are OS/browser-specific — generate baseline screenshots in the same environment as CI (use Docker).
- Font rendering differs between OSes — use '--ignore-fonts' or run tests in containers.
- First run without baseline generates the snapshot — commit it to source control.
Revisions (0)
No revisions yet.