Headless browsers are fully capable of taking screenshots, which is very useful in troubleshooting failures or faulty scripts. Using additional libraries and tools, it is also possible to automate visual comparisons.

Generating and saving screenshots

The page.screenshot command allows us to save one or more screenshots of the current page to a specified path. Without any additional options, the size of the screenshot depends on the viewport size:
basic-screenshot.spec.ts
// Example code - see original file for details

Full page screenshots

Adding the fullPage: true option allows for the capture of full page screenshots, overriding the height parameter specified for our viewport:
await page.screenshot({ path: 'my_screenshot.png', fullPage: true })

Clipped screenshots

Having our screenshot limited to a smaller portion of the viewport is also possible. All we need to do is specify the coordinates of the top left corner of the screenshot, plus width and height. We then pass these options to:
basic-screenshot-clipped.spec.ts
// Example code - see original file for details
The above examples can be run as follows:
npx playwright test basic-screenshots.spec.ts

Visual regression testing

Playwright can be used to take screenshots of a page and compare them with a reference image. This is useful for visual regression testing, where we can detect changes in the UI that may have been introduced by code changes. The expect(page).toMatchSnapshot() command is used to take a screenshot and compare it with a reference image. If the images are different, the test will fail.
visual-regression.spec.ts
// Example code - see original file for details

Further reading

  1. Official documentation for taking screenshots with Playwright
  2. Blog post from baseweb.design on the whys and hows of visual regression testing
  3. Blog post from Gideon Pyzer looking at different visual regression testing tools