Detect unintended visual changes in UI components by capturing screenshots and comparing them pixel-by-pixel against approved baselines. Supports Playwright visual comparisons, Percy, Chromatic, BackstopJS, and reg-suit.
toHaveScreenshot, Percy, Chromatic, or BackstopJS)* { animation: none !important; transition: none !important; }).fullPage: true for scrollable pages.--update-snapshots.__screenshots__/ or equivalent directory| Error | Cause | Solution |
|---|---|---|
| Anti-aliasing differences across OS | Font rendering varies between macOS, Linux, and Windows | Run visual tests in Docker with fixed fonts; use threshold option to allow sub-pixel variance |
| Flaky screenshots from animations | CSS transitions or JS animations still running at capture time | Inject prefers-reduced-motion or disable animations via addStyleTag before capture |
| Missing baseline on first run | No previous screenshot exists to compare against | Run with --update-snapshots to create initial baselines; commit them to the repository |
| Viewport size mismatch | Browser chrome or scrollbar width differs between environments | Use setViewportSize explicitly; hide scrollbars with CSS overflow: hidden |
| Dynamic content causes false failures | Timestamps, user avatars, or ads change between runs | Mask dynamic elements with mask option or replace content via page.evaluate |
Playwright visual regression test:
import { test, expect } from '@playwright/test';
test('homepage matches baseline', async ({ page }) => {
await page.goto('/');
await page.waitForLoadState('networkidle');
await page.addStyleTag({ content: '* { animation: none !important; }' });
await expect(page).toHaveScreenshot('homepage.png', {
maxDiffPixelRatio: 0.001,
fullPage: true,
});
});
BackstopJS scenario configuration:
{
"label": "Login Page",
"url": "http://localhost:3000/login", # 3000: 3 seconds in ms
"selectors": ["document"],
"misMatchThreshold": 0.1,
"viewports": [
{ "label": "phone", "width": 375, "height": 812 }, # 812: 375 = configured value
{ "label": "desktop", "width": 1280, "height": 720 } # 1280: 720 = configured value
]
}