Visual Comparison Testing
Relevant source files
The following files were used as context for generating this wiki page:
- packages/playwright/src/matchers/toMatchSnapshot.ts
- tests/playwright-test/to-have-screenshot.spec.ts
- packages/playwright-core/src/server/screenshotter.ts
- tests/playwright-test/golden.spec.ts
- packages/playwright/types/test.d.ts
- tests/playwright-test/reporter-html.spec.ts
- packages/web/src/components/codeMirrorWrapper.spec.tsx
- tests/playwright-test/reporter-list.spec.ts
Visual Comparison Testing, also known as Snapshot Testing, is a feature in Playwright that helps detect unintended visual changes in a user interface. It works by taking a screenshot or a snapshot of a UI component or a whole page and comparing it to a "golden" or reference snapshot stored alongside the test code. If the new snapshot differs from the golden one, the test fails. This is an effective way to ensure UI consistency and prevent visual regressions.
This system supports both image-based and text-based snapshots. The primary assertion for images is expect(page).toHaveScreenshot(), while expect(value).toMatchSnapshot() is a more generic matcher for any serializable value, including text and binary data. When a visual test fails, Playwright generates a detailed diff report, making it easy to review the changes. The behavior can be configured through the test configuration file, command-line flags, and options within the assertion calls themselves.
Core Concepts
The Snapshot Workflow
The visual comparison process follows a defined workflow for creating, comparing, and updating snapshots.
This diagram illustrates the logic of the toMatchSnapshot assertion.
This flowchart shows the decision-making process during a snapshot assertion.
Sources: tests/playwright-test/golden.spec.ts:243-260, tests/playwright-test/golden.spec.ts:281-294
- Initial Run: If a snapshot does not exist, it is created from the actual value. The test runner will report a failure indicating a missing snapshot unless the
--update-snapshotsflag is used, in which case it creates the snapshot and passes the test. - Subsequent Runs: If a snapshot exists, the actual value is compared to the existing snapshot.
- Match: If the actual value matches the snapshot, the test passes.
- Mismatch: If the actual value does not match, the test fails. A diff is generated, and
actual,expected, anddiffartifacts are saved to the test output directory. - Updating Snapshots: The
--update-snapshotscommand-line flag can be used to overwrite existing snapshots with the new actual values.
Snapshot Naming and Location
Snapshots are stored in a directory named <test-file-name>-snapshots next to the test file. The name of the snapshot file can be provided explicitly in the assertion or generated automatically.
- Explicit Naming:
expect(value).toMatchSnapshot('my-snapshot.txt') - Automatic Naming:
expect(value).toMatchSnapshot()will generate a name liketest-name-1.txt.
The location and naming convention can be customized using snapshotDir and snapshotPathTemplate in the configuration.
Sources: tests/playwright-test/golden.spec.ts:46-71, packages/playwright/types/test.d.ts:439-519
Assertions API
Playwright provides two main assertions for visual testing.
expect(value).toMatchSnapshot()
This is a generic assertion that can be used for any value, including strings and buffers. It automatically determines the file extension based on the content type.
string->.txtBuffer(PNG) ->.pngBuffer(JPEG) ->.jpg- Other
Buffer->.dat
Sources: tests/playwright-test/golden.spec.ts:46-71
expect(page).toHaveScreenshot() and expect(locator).toHaveScreenshot()
These are specialized assertions for taking and comparing screenshots of a page or a specific element. They offer more control over the screenshot process.
Key options for toHaveScreenshot:
| Option | Type | Description |
|---|---|---|
animations | "disabled" | "allow" | Disables or allows CSS and Web Animations. Defaults to "disabled". |
caret | "hide" | "initial" | Hides the text caret. Defaults to "hide". |
mask | Array<Locator> | Specifies locators to be masked with a pink box. |
maxDiffPixels | number | The maximum number of pixels that can be different. |
maxDiffPixelRatio | number | The maximum ratio of different pixels to the total number of pixels. |
threshold | number | An acceptable perceived color difference between pixels (0 to 1). Defaults to 0.2. |
fullPage | boolean | Whether to take a screenshot of the full scrollable page. |
scale | "css" | "device" | Scaling behavior for high-dpi devices. Defaults to "css". |
Sources: packages/playwright/types/test.d.ts:1691-1804
Configuration
Visual comparison behavior can be configured globally in playwright.config.ts.
| Configuration | Type | Description |
|---|---|---|
expect.timeout | number | Default timeout for async expect matchers. |
expect.toHaveScreenshot | object | Default options for toHaveScreenshot assertions. |
expect.toMatchSnapshot | object | Default options for toMatchSnapshot assertions. |
snapshotDir | string | Base directory for snapshot files. |
snapshotPathTemplate | string | Template for snapshot file paths. |
updateSnapshots | "all"|"changed"|"missing"|"none" | Controls when to update snapshots. |
ignoreSnapshots | boolean | If true, skips all snapshot assertions. |
Sources: packages/playwright/types/test.d.ts:600-681, packages/playwright/types/test.d.ts:439-449
The snapshotPathTemplate allows for flexible organization of snapshot files using tokens like {testDir}, {testFilePath}, {arg}, {projectName}, and {platform}.
Sources: packages/playwright/types/test.d.ts:451-519
Reporting and Diffing
When a visual comparison test fails, Playwright provides rich reporting to help diagnose the changes.
Test Attachments
On failure, the following files are attached to the test result:
*-expected.*: The golden snapshot.*-actual.*: The actual image or text generated during the test run.*-diff.*: A visual diff image highlighting the differences (for image snapshots).
These attachments are crucial for both local debugging and CI reports.
Sources: tests/playwright-test/golden.spec.ts:182-205, tests/playwright-test/golden.spec.ts:540-571
HTML Report
The HTML reporter provides an interactive interface for reviewing visual differences.
This sequence diagram shows the flow from a test failure to viewing the diff in the HTML report.
The diff viewer in the HTML report includes several modes to inspect the changes:
- Diff: Shows a blended view of the expected and actual images with differences highlighted in red.
- Actual: Shows the screenshot captured during the test run.
- Expected: Shows the golden screenshot.
- Side by side: Displays the expected and actual images next to each other.
- Slider: An interactive slider to swipe between the expected and actual images.
For textual snapshots, the report displays a color-coded diff (green for removed lines, red for added lines).
Sources: tests/playwright-test/reporter-html.spec.ts:196-228, tests/playwright-test/reporter-html.spec.ts:1143-1154
Command-Line Interface
The test runner's behavior regarding snapshots can be controlled via CLI flags.
| Flag | Description |
|---|---|
--update-snapshots | Updates all failing snapshots with the new actual content. |
--ignore-snapshots | Skips all snapshot assertions, making them pass. |
The updateSnapshots option in the configuration file provides more granular control ('all', 'changed', 'missing', 'none').
Sources: tests/playwright-test/golden.spec.ts:281-294, tests/playwright-test/golden.spec.ts:318-335, packages/playwright/types/test.d.ts:899-918
Summary
Playwright's visual comparison testing is a powerful tool for ensuring UI stability. By integrating snapshot generation, comparison, and rich diff reporting directly into the test runner, it provides a seamless workflow for developers to catch and review visual regressions. The system is highly configurable, supporting various data types, custom naming conventions, and detailed comparison options, making it adaptable to a wide range of testing needs. The interactive HTML report is particularly valuable for quickly identifying the root cause of visual discrepancies.