πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Questions
Question 83 of 100
Debugging
Intermediate

How do screenshots and videos work in Playwright?

The Answer

Playwright supports manual screenshots via `page.screenshot()` and automatic screenshots via configuration. Videos are recorded at the browser context level and finalized when the context closes.

Deep Dive Explanation

Visual regression with `toHaveScreenshot()` creates a baseline image on first run (update with `--update-snapshots`). Subsequent runs compare against the baseline. This catches unintended CSS changes that functional tests miss.

example.spec.ts
// Manual screenshot
await page.screenshot({ path: 'homepage.png' });
await page.screenshot({ path: 'full-page.png', fullPage: true });

// Element screenshot
await page.locator('.chart-widget').screenshot({ path: 'chart.png' });

// Config-based automatic screenshots
export default defineConfig({
  use: {
    screenshot: 'only-on-failure', // or 'on', 'off'
    video: 'retain-on-failure',    // or 'on', 'off', 'on-first-retry'
  },
});

// Visual regression (compare to baseline)
await expect(page).toHaveScreenshot('dashboard.png', {
  maxDiffPixels: 100,    // Allow 100 pixels to differ
  threshold: 0.1,        // 10% pixel color difference tolerance
});