Frames and Files
Screenshots in Playwright
Screenshots in Playwright: definition, page and element Screenshots, debugging usage, mistakes, interview notes, and practice.
Definition and Brief Explanation
Definition: Screenshots in Playwright capture the current page, a full page, or a specific element as an image file.
Explanation: Screenshots are useful for debugging failures, visual evidence, documentation, and comparing UI state. They should support test diagnosis, not replace meaningful assertions.
Why It Matters
- It captures visual evidence when a test fails.
- It helps compare expected and actual page state during debugging.
- It can document important UI states during test execution.
- It supports element-level checks when only one part of the page matters.
How It Works
- Choose page screenshot, full-page screenshot, or locator screenshot.
- Save the image to a predictable test output path.
- Capture screenshots mainly on failure or meaningful checkpoints.
- Use screenshots together with assertions, not instead of assertions.
Syntax and Examples
Example 1: Page screenshot
await page.screenshot({ path: 'home.png', fullPage: true });
Explanation: Captures the full page as evidence.
Example 2: Element screenshot
await page.getByTestId('invoice').screenshot({ path: 'invoice.png' });
Explanation: Captures one element or component.
Common Mistakes
- Using screenshots as the only proof of success.
- Saving screenshots to unstable paths.
- Taking too many screenshots and slowing CI.
- Confusing screenshots with true visual regression testing.
Interview Notes
- How do you capture a full-page screenshot?
- How do you capture only one element?
- When should screenshots be enabled in CI?
- Why should screenshots not replace assertions?
Practice Task
Capture a screenshot after a failed validation message appears. Also capture only the message element and compare which one is more useful for debugging.