How do I take a screenshot when a Playwright test fails?
Written by Jatin Thacker, Automation Architect · Updated
This answer is one piece of Chapter 26: Reporting.
- HTML Reports & Custom Reporters
- Allure: Reports for Managers
- JUnit XML for CI Dashboards
Visual evidence is essential for diagnosing test failures in CI. Rather than writing manual try/catch blocks or afterEach hooks, Playwright provides native declarative configuration for automatic failure screenshots.
In playwright.config.ts or within an individual spec file via test.use(), set screenshot: 'only-on-failure' inside the use options. When a test passes, no screenshot is captured, avoiding unnecessary disk and CPU overhead. When an assertion or action fails, Playwright captures the viewport at the end of the failed test run.
The resulting image is saved into your test artifact directory (test-results/) and attached to the run report. You can also capture on-demand screenshots during normal execution by calling await page.screenshot({ path: 'screenshot.png' }).
import { test, expect } from '@playwright/test';
test.use({ screenshot: 'only-on-failure' });
test('captures screenshot on assertion failure', async ({ page }) => {
await page.goto('/catalog.html?mock=static&seed=42');
await expect(page.locator('#missing-element')).toBeVisible({ timeout: 1000 });
});Running 1 test using 1 worker
x 1 screenshot-failure.spec.js:5:1 › captures screenshot on assertion failure (2.1s)
1) screenshot-failure.spec.js:5:1 › captures screenshot on assertion failure ───────
Error: expect(locator).toBeVisible() failed
Locator: locator('#missing-element')
Expected: visible
Timeout: 1000ms
Error: element(s) not found
attachment #1: screenshot (image/png) ──────────────────────────────────────────────────────────
test-results/screenshot-failure-captures-screenshot-on-assertion-failure/test-failed-1.png
────────────────────────────────────────────────────────────────────────────────────────────────
1 failedtry/catch blocks?Related questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free