Playwright · Reliable end-to-end tests
How does visual testing work with toHaveScreenshot?
Short answer
Playwright compares a screenshot against a committed baseline and fails on a difference beyond the configured threshold. Run it in a consistent environment and mask dynamic regions.
toHaveScreenshot captures the current UI, compares it with a stored baseline for that browser and platform, and fails when the difference exceeds the configured tolerance. It is useful for catching layout and styling regressions that behaviour assertions miss.
await expect(page).toHaveScreenshot("checkout.png", {
maxDiffPixelRatio: 0.01,
animations: "disabled",
mask: [page.getByTestId("timestamp")],
});Options that keep it stable
maxDiffPixelsormaxDiffPixelRatioto allow a small amount of noisethresholdto control per-pixel colour sensitivityanimations: "disabled"to freeze transitions and CSS animationsmaskto hide timestamps, avatars and other dynamic contentfullPageto compare the whole scrollable page rather than the viewport
Screenshots are environment-sensitive. Fonts, browser version, operating system, device scale factor and locale all affect rendering. Run the comparison in a consistent container or CI image, and keep a separate baseline per project so Chromium and WebKit do not overwrite each other.
npx playwright test --update-snapshots
npx playwright show-reportFollow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why do screenshot baselines differ between operating systems?
- 2When would you use maxDiffPixelRatio?
- 3How do you handle a timestamp in a screenshot?
- 4Why should updating snapshots be a review step?
Say it in the interview
toHaveScreenshot compares the current render to a stored baseline and fails when the difference exceeds the configured tolerance. I disable animations and mask dynamic content, and I run it in a consistent environment because fonts and rendering differ across platforms. Baselines are stored per project, so Chromium and WebKit do not collide. I update snapshots deliberately and review the diff, never automatically on every failure.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Playwright mock interview and get scored feedback on depth, clarity and confidence.