Screenshots
I use screenshots for two things: debugging (save a screenshot when something looks wrong) and visual regression (compare against a golden image). Two completely different use cases, two different APIs.
Capture a screenshot
The most common use: save a screenshot to a file for debugging. Use it when a test fails and you want to see what the page looked like at that moment.
Auto-screenshot on failure
Instead of adding page.screenshot() calls throughout your tests, configure Playwright to save screenshots automatically on failure. The screenshot is attached to the test report — you see it right next to the failed test.
Visual regression with toHaveScreenshot
For visual regression tests — "does the dashboard look the same as before" — use toHaveScreenshot. On the first run it saves a golden image. On subsequent runs it compares pixel by pixel. If they differ beyond the threshold, the test fails.
Visual tests are fragile — fonts, colors, anti-aliasing differ across OS and GPU. Best practice: run visual tests in a fixed Docker environment, not local machines.