Playwright Visual Comparison
A quality inspector at a printing press checks a finished poster against the original design file, spotting a shifted logo or a missing image at a glance. Visual comparison testing gives Playwright that same eye for spotting layout problems a text-based check would completely miss.
How Visual Comparison Works
Saved Baseline Image
|
v
Pixel-by-Pixel Comparison
^
|
Current Page Screenshot
|
+----+----+
| |
Match Difference Found
Taking a Full Page Screenshot Comparison
await expect(page).toHaveScreenshot('homepage.png');The first time this line runs, Playwright saves a new baseline image named "homepage.png." Every future run compares the live page against that saved image.
Comparing Only One Section
await expect(page.locator('.hero-banner')).toHaveScreenshot('hero-banner.png');This checks only the top banner section, ignoring the rest of the page. This works well when other sections, such as a rotating list of articles, change frequently and would cause constant false failures.
A Real-World Scenario
A developer updates the website's CSS file to fix a spacing issue on the contact page. The change accidentally shifts the logo on every other page by ten pixels. A text-based test would still pass, since the logo's text and link still work correctly. A visual comparison test catches this shift immediately.
Allowing Small Rendering Differences
await expect(page).toHaveScreenshot('homepage.png', {
maxDiffPixelRatio: 0.02,
});Fonts can render with tiny differences across operating systems. This setting allows up to two percent pixel difference before marking the test as failed, avoiding false alarms over harmless rendering variations.
Updating a Baseline Image
npx playwright test --update-snapshotsAfter an intentional design change, run this command once to save a new baseline image matching the updated design. Every future test then compares against this new, correct version.
Where Baseline Images Live
Playwright saves baseline images inside a folder next to the test file, usually named after the test itself. This folder should get committed alongside the test code so every team member compares against the same reference images.
Quick Practice Task
Pick a simple, stable webpage and write a visual comparison test for its main banner section. Run the test twice and confirm it passes both times.
Key Takeaways
- Visual comparison checks pixels, catching layout bugs text checks miss.
- A baseline image sets the expected appearance for future comparisons.
- Single elements can be tested instead of the entire page.
- A small pixel tolerance avoids false failures from font rendering.
