IKivan-kozenko -aqa
Try yourself as a QA tester
All topics·Beginner·15 / 16

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.

ts
// Весь viewport
await page.screenshot({ path: '/tmp/debug.png' })

// Вся сторінка (зі скролом)
await page.screenshot({ path: '/tmp/full-page.png', fullPage: true })

// Конкретний елемент
await page.locator('[data-testid="order-card"]').screenshot({ path: '/tmp/card.png' })

// Отримати як Buffer (без збереження)
const buffer = await page.screenshot()
// можна відправити кудись або зробити base64
console.log(buffer.toString('base64'))

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.

ts
// playwright.config.ts
export default defineConfig({
  use: {
    // 'off' — не знімати (за замовчуванням)
    // 'on' — знімати завжди
    // 'only-on-failure' — тільки при падінні
    screenshot: 'only-on-failure',
  },
})

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.

ts
test('order dashboard looks correct', async ({ page }) => {
  await page.goto('/dashboard')
  await page.waitForLoadState('networkidle') // чекаємо всіх завантажень

  // Перший запуск: зберігає dashboard.png як еталон
  // Наступні запуски: порівнює з еталоном
  await expect(page).toHaveScreenshot('dashboard.png')
})

// Для конкретного компонента
test('order card renders correctly', async ({ page }) => {
  await page.goto('/orders/42')

  const card = page.getByTestId('order-card')
  await expect(card).toHaveScreenshot('order-card.png', {
    maxDiffPixelRatio: 0.02, // допускаємо 2% відхилення
  })
})

// Оновити еталонні зображення
// npx playwright test --update-snapshots