Vitest 27 🧪 Visual Regression — toMatchScreenshot and toBeInViewport
Visual regression testing catches the class of bug that assertions on the DOM cannot: a button that is the right element with the right text but the wrong color, a layout that shifts by two pixels after a CSS refactor, a component that renders correctly in jsdom but collapses in a real browser. Unit tests operate on the abstract tree; visual tests operate on the painted pixels. The two are complementary, and Vitest ships both halves of the story — a screenshot comparison for captured images and a viewport assertion for whether an element is actually visible to the user.
This chapter covers toMatchScreenshot, the browser-mode matcher that captures a screenshot of an element or the page and compares it against a stored baseline, and toBeInViewport, the matcher that asserts an element intersects the visible viewport. It walks through the prerequisites (browser mode is required for both), the baseline workflow, the threshold and comparator options, and the CI story for updating snapshots. The sections that follow explain the screenshot matcher, the viewport matcher, and the baseline update lifecycle.
Key point: toMatchScreenshot and toBeInViewport are browser-mode matchers; the screenshot matcher captures pixels and compares them to a committed baseline with a configurable threshold, and the viewport matcher asserts geometric intersection. Both require a real browser via the Playwright provider, and both fail in jsdom.
Why visual regression exists
The jsdom blind spot. Unit tests run in jsdom, which has no layout engine. getBoundingClientRect() returns zeros, CSS is not applied to geometry, and an element can be “present” while being invisible, zero-sized, or pushed off-screen. A test that asserts expect(button).toBeInTheDocument() passes even when the button has display: none or sits under another element. The viewport matcher fills that gap by asking the real browser whether the element occupies visible space.
The CSS regression problem. A stylesheet refactor can change the rendered output without touching a single line of component logic. The DOM assertion still passes, but the page looks wrong. The screenshot matcher catches this because it compares the painted result, not the tree that produced it. The baseline is the committed image; the diff is the regression.
The baseline-as-artifact trade-off. A screenshot baseline is a binary file in the repository. It must be regenerated when the UI changes intentionally, and it must be reviewed like code. The trade-off is real: visual tests are slower and noisier than unit tests, and a flaky font render or a different OS can produce false positives. The threshold and the comparator options exist to absorb that noise, but they also mask real regressions if set too loose.
The browser-mode requirement. Neither matcher works in jsdom because neither has pixels or a viewport to reason about. Vitest’s browser mode runs the tests in a real browser via the Playwright provider, and only there do toMatchScreenshot and toBeInViewport have meaning. The cost is setup and speed; the benefit is that the assertions test what the user sees.
The CI determinism problem. A screenshot taken on a developer’s macOS with a retina display will not match a baseline taken on a Linux CI runner with a different font stack. The solution is to generate baselines in the same environment that verifies them — typically the CI container — and to keep the environment pinned. The resolveScreenshotPath and comparator configuration are the knobs for that.
The accessibility link. toBeInViewport is also a cheap accessibility check. An element that is not in the viewport is not visible to a sighted user, and the assertion is a fast way to catch content that is hidden behind a sticky header, clipped by overflow: hidden, or positioned outside the scroll area. It does not replace a screen-reader test, but it catches the geometric half of the problem.
a. The toMatchScreenshot matcher
toMatchScreenshot captures a screenshot of an element or the page and compares it to a stored baseline image. It requires browser mode; in jsdom it throws because there is no renderer to capture. The matcher is available from @vitest/browser/context and is registered automatically when browser mode is enabled.
// Requires browser mode: vitest --browser
import { test, expect } from "vitest";
import { page } from "@vitest/browser/context";
test("button renders with the correct style", async () => {
// Mount the component into the real browser DOM
document.body.innerHTML = `<button class="primary">Submit</button>`;
// Capture the button and compare against the stored baseline
await expect(page.getByRole("button")).toMatchScreenshot("primary-button");
});
The first argument is the baseline name. Vitest stores the image under __screenshots__/ next to the test file, using the name and the platform suffix. The first run writes the baseline and passes; subsequent runs compare against it. A mismatch fails with the diff path printed.
The matcher accepts an options object as the second argument. The comparator option selects the pixel-diff algorithm, and the allowedMismatchedPixelRatio bounds how much of the image may differ before the test fails.
await expect(page.getByRole("button")).toMatchScreenshot("primary-button", {
// Allow up to 1% of pixels to differ (anti-aliasing, subpixel font rendering)
comparator: "pixelmatch",
allowedMismatchedPixelRatio: 0.01,
// Clip to a specific region so only the button is compared
screenshotOptions: {
clip: { x: 0, y: 0, width: 200, height: 80 },
},
});
The clip option is the tool for stabilizing a screenshot. A full-page capture is sensitive to every scrollbar and layout shift on the page; a clipped capture isolates the element under test. The omitBackground and scale options in screenshotOptions cover the transparent-background and device-pixel-ratio cases.
The matcher also works on the full page. page.screenshot() captures the viewport, and expect(page).toMatchScreenshot(...) is the page-level form. The element form is the recommendation because it scopes the comparison and reduces flakiness.
b. The toBeInViewport matcher
toBeInViewport asserts that an element intersects the visible viewport. It is a geometric check: it asks the browser whether the element’s bounding box overlaps the viewport rectangle. It requires browser mode because jsdom has no layout, and an element in jsdom has a zero-sized box that trivially fails or passes depending on the implementation.
import { test, expect } from "vitest";
import { page } from "@vitest/browser/context";
test("hero section is visible on load", async () => {
// The hero is above the fold; it must intersect the viewport
await expect(page.getByRole("heading", { name: "Welcome" })).toBeInViewport();
});
test("footer is below the fold", async () => {
// The footer is out of view until the user scrolls
await expect(page.getByRole("contentinfo")).not.toBeInViewport();
});
The matcher accepts an options object with ratio, which is the fraction of the element that must be visible. The default is 0, meaning any intersection at all passes. A ratio: 1 requires the element to be fully visible; a ratio: 0.5 requires at least half of it.
// Require the whole card to be visible, not just its top edge
await expect(page.getByTestId("pricing-card")).toBeInViewport({ ratio: 1 });
// Require at least half of the banner to be visible
await expect(page.getByTestId("cookie-banner")).toBeInViewport({ ratio: 0.5 });
The matcher does not scroll. It checks the current state, so a test that wants to assert “the element becomes visible after scrolling” must scroll first with element.scrollIntoView() and then assert. The matcher also does not account for occlusion: an element covered by a modal is still “in the viewport” geometrically. For occlusion, a screenshot or a document.elementFromPoint check is the stronger assertion.
The toBeInViewport matcher is the fast, cheap check that pairs with the screenshot matcher. The viewport matcher answers “is it on screen”; the screenshot matcher answers “does it look right.” Together they cover the visible half of the UI contract.
c. The baseline lifecycle and CI
The baseline is the artifact that makes the screenshot matcher useful. It is a committed image, and it must be regenerated intentionally when the UI changes. Vitest’s update flow is the -u flag, which rewrites the baselines for the tests that run. The flag is the same one that updates inline snapshots, and it is the reason the visual tests belong in the same suite as the unit tests.
# Write the baselines on the first run
vitest --browser -u
# Verify against the committed baselines in CI
vitest --browser
The toMatchScreenshot matcher writes to __screenshots__/<test-file>/<name>-<platform>.png by default. The platform suffix exists because the rendering differs across operating systems, and a baseline captured on macOS will not match Linux. The recommendation is to generate baselines in the same container that CI uses, so the fonts and the renderer match.
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
browser: {
enabled: true,
provider: "playwright",
instances: [{ browser: "chromium" }],
// Pin the viewport so screenshots are deterministic
viewport: { width: 1280, height: 720 },
// Generate and verify baselines in the same CI container
screenshotOptions: {
animations: "disabled", // freeze CSS animations
caret: "hide", // hide the text cursor
scale: "css", // use CSS pixels, not device pixels
},
},
},
});
The animations: "disabled" option is the most important stabilizer. A screenshot taken mid-transition captures a frame that will never recur, and the baseline becomes flaky. Disabling animations freezes the element at its final state. The caret: "hide" option removes the blinking cursor, which is the other common source of one-pixel diffs.
The resolveScreenshotPath option is the hook for a custom baseline layout. The default path is colocated with the test, but a team that wants a single __screenshots__/ root can override it. The function receives the test file, the baseline name, and the browser name, and returns the absolute path.
// vitest.config.ts
export default defineConfig({
test: {
browser: {
expect: {
toMatchScreenshot: {
// Centralize all baselines under one root
resolveScreenshotPath: ({ testFile, arg, browserName }) =>
`__screenshots__/${browserName}/${arg}.png`,
},
},
},
},
});
The CI story is the last piece. A visual test that fails in CI must produce the diff image, and the diff must be uploaded as an artifact so a reviewer can see what changed. The onTestFailed hook is the place to copy the diff, and the CI artifact upload is the mechanism that surfaces it in the pull request.
import { afterEach } from "vitest";
import { copyFile } from "node:fs/promises";
afterEach(async (context) => {
// On a screenshot failure, copy the diff to an uploadable location
if (context.task.result?.state === "fail") {
const diff = context.task.meta.screenshotDiff;
if (diff) await copyFile(diff, `artifacts/${context.task.id}-diff.png`);
}
});
Complete Example Session
// ============================================
// PART 1: THE CONFIGURATION
// ============================================
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
browser: {
enabled: true,
provider: "playwright",
instances: [{ browser: "chromium" }],
viewport: { width: 1280, height: 720 },
screenshotOptions: {
animations: "disabled", // freeze transitions before capture
caret: "hide", // hide the blinking text cursor
},
},
},
});
// ============================================
// PART 2: THE ELEMENT SCREENSHOT
// ============================================
import { test, expect } from "vitest";
import { page } from "@vitest/browser/context";
test("primary button matches the baseline", async () => {
document.body.innerHTML = `<button class="primary">Submit</button>`;
// Capture the button element, not the whole page
await expect(page.getByRole("button")).toMatchScreenshot("primary-button");
});
// ============================================
// PART 3: THE THRESHOLD
// ============================================
test("button tolerates anti-aliasing noise", async () => {
document.body.innerHTML = `<button class="primary">Submit</button>`;
await expect(page.getByRole("button")).toMatchScreenshot("primary-button", {
// Allow 1% of pixels to differ before failing
allowedMismatchedPixelRatio: 0.01,
comparator: "pixelmatch",
});
});
// ============================================
// PART 4: THE CLIPPED CAPTURE
// ============================================
test("only the card region is compared", async () => {
document.body.innerHTML = `<div data-testid="card">...</div>`;
await expect(page.getByTestId("card")).toMatchScreenshot("card", {
screenshotOptions: {
// Clip to the card's rectangle to ignore page-level noise
clip: { x: 0, y: 0, width: 400, height: 300 },
},
});
});
// ============================================
// PART 5: THE VIEWPORT CHECK
// ============================================
test("hero heading is above the fold", async () => {
document.body.innerHTML = `<h1>Welcome</h1>`;
// Any intersection with the viewport passes
await expect(page.getByRole("heading")).toBeInViewport();
});
// ============================================
// PART 6: THE RATIO CHECK
// ============================================
test("pricing card is fully visible", async () => {
document.body.innerHTML = `<div data-testid="pricing">...</div>`;
// Require the entire card, not just its top edge
await expect(page.getByTestId("pricing")).toBeInViewport({ ratio: 1 });
});
// ============================================
// PART 7: THE NEGATIVE ASSERTION
// ============================================
test("footer is out of view initially", async () => {
document.body.innerHTML = `<footer>© 2025</footer>`;
// The footer is below the fold at load
await expect(page.getByRole("contentinfo")).not.toBeInViewport();
});
// ============================================
// PART 8: THE SCROLL-THEN-ASSERT
// ============================================
test("footer becomes visible after scrolling", async () => {
document.body.innerHTML = `<footer>© 2025</footer>`;
const footer = page.getByRole("contentinfo");
// Scroll the element into view, then assert
await footer.scrollIntoView();
await expect(footer).toBeInViewport();
});
// ============================================
// PART 9: THE CI ENVIRONMENT PIN
// ============================================
// The CI workflow runs the same container that wrote the baselines
// .github/workflows/visual.yml
// jobs:
// visual:
// runs-on: ubuntu-latest
// container: mcr.microsoft.com/playwright:v1.49.0-jammy
// steps:
// - run: vitest --browser
// ============================================
// PART 10: THE DIFF ARTIFACT
// ============================================
import { afterEach } from "vitest";
import { copyFile } from "node:fs/promises";
afterEach(async (context) => {
// Copy the diff image so CI can upload it
if (context.task.result?.state === "fail") {
const diff = context.task.meta.screenshotDiff;
if (diff) await copyFile(diff, `artifacts/${context.task.id}.png`);
}
});
The ten parts covered the browser-mode configuration, the element screenshot, the threshold, the clipped capture, the viewport check, the ratio check, the negative assertion, the scroll-then-assert pattern, the CI container pin, and the diff artifact.
Quick Reference
Matchers
| Matcher | Purpose | Requirement |
|---|---|---|
toMatchScreenshot(name) | Compare pixels to a baseline | Browser mode |
toBeInViewport(opts) | Assert viewport intersection | Browser mode |
not.toMatchScreenshot | Assert a pixel difference | Browser mode |
not.toBeInViewport | Assert no intersection | Browser mode |
Screenshot Options
| Option | Effect |
|---|---|
comparator | Pixel-diff algorithm (pixelmatch) |
allowedMismatchedPixelRatio | Fraction of pixels allowed to differ |
screenshotOptions.clip | Capture a region only |
screenshotOptions.scale | CSS pixels vs device pixels |
Viewport Options
| Option | Effect |
|---|---|
ratio | Fraction of element that must be visible |
default ratio: 0 | Any intersection passes |
ratio: 1 | Entire element must be visible |
CLI and Config
| Item | Effect |
|---|---|
vitest --browser | Run the browser tests |
vitest --browser -u | Rewrite the baselines |
browser.screenshotOptions | Global capture defaults |
resolveScreenshotPath | Custom baseline location |
Best Practices
✅ Do This:
// Capture the element, not the whole page
await expect(page.getByRole("button")).toMatchScreenshot("btn"); // ✅
// Freeze animations before capture
screenshotOptions: { animations: "disabled" }; // ✅
// Generate baselines in the CI container
container: mcr.microsoft.com/playwright:v1.49.0-jammy; // ✅
// Bound the pixel tolerance
allowedMismatchedPixelRatio: 0.01; // ✅
// Use ratio for partial visibility
await expect(card).toBeInViewport({ ratio: 0.5 }); // ✅
// Scroll before asserting visibility
await footer.scrollIntoView(); // ✅
❌ Don’t Do This:
// Use the matcher in jsdom
await expect(el).toMatchScreenshot("btn"); // ❌
// Capture a full page with animations running
screenshotOptions: { animations: "allow" }; // ❌
// Generate on macOS, verify on Linux
// (fonts differ, baselines never match) // ❌
// Set a loose tolerance to hide real bugs
allowedMismatchedPixelRatio: 0.5; // ❌
// Expect the matcher to scroll
await expect(footer).toBeInViewport(); // without scroll // ❌
// Treat viewport as an occlusion check
// (a covered element is still in the viewport) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Matcher throws “not available” | jsdom mode | Enable browser mode |
| Flaky screenshot | Animations or caret captured | animations: "disabled" |
| Baseline never matches | Different OS or font stack | Same CI container |
| Threshold masks a bug | Tolerance too loose | Lower allowedMismatchedPixelRatio |
| Viewport passes on hidden element | No occlusion check | Use elementFromPoint or screenshot |
| Viewport fails after scroll test | Matcher does not scroll | Call scrollIntoView() first |
| Huge diff images | Full-page capture | Clip to the element |
| Baseline lost in review | Binary in PR | Upload diff as artifact |
Real-World Examples
1. Element baseline
await expect(page.getByRole("button")).toMatchScreenshot("btn");
2. Page baseline
await expect(page).toMatchScreenshot("landing-page");
3. Tolerant comparison
await expect(el).toMatchScreenshot("card", {
allowedMismatchedPixelRatio: 0.01,
});
4. Clipped capture
await expect(el).toMatchScreenshot("card", {
screenshotOptions: { clip: { x: 0, y: 0, width: 400, height: 300 } },
});
5. Any intersection
await expect(page.getByRole("heading")).toBeInViewport();
6. Full visibility
await expect(page.getByTestId("card")).toBeInViewport({ ratio: 1 });
7. Partial visibility
await expect(page.getByTestId("banner")).toBeInViewport({ ratio: 0.5 });
8. Out-of-view assertion
await expect(page.getByRole("contentinfo")).not.toBeInViewport();
9. Scroll then assert
await footer.scrollIntoView();
await expect(footer).toBeInViewport();
10. Baseline update
vitest --browser -u
Visual
The Capture and Compare Flow
┌─────────────────────────────────────────────────────────┐
│ toMatchScreenshot FLOW │
│ │
│ test runs in browser mode │
│ │ │
│ ▼ │
│ capture element pixels │
│ │ │
│ ▼ │
│ load baseline from __screenshots__/ │
│ │ │
│ ▼ │
│ pixel-diff with comparator │
│ │ │
│ ┌────┴────┐ │
│ ▼ ▼ │
│ match mismatch │
│ pass fail + diff path │
└─────────────────────────────────────────────────────────┘
The Viewport Geometry
┌─────────────────────────────────────────────────────────┐
│ VIEWPORT (1280 × 720) │
│ │
│ ┌─────────────────────┐ ← heading: ratio 1 passes │
│ │ heading │ │
│ └─────────────────────┘ │
│ │
│ ┌─────────────────────┐ │
│ │ card (half cut) │ ← ratio 0.5 passes │
│ ├─────────────────────┤ ratio 1 fails │
│ │
│ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ │
│ footer (below fold) ← not.toBeInViewport passes │
└─────────────────────────────────────────────────────────┘
The Baseline Lifecycle
┌─────────────────────────────────────────────────────────┐
│ FIRST RUN SUBSEQUENT RUNS │
│ vitest --browser -u vitest --browser │
│ │ │ │
│ ▼ ▼ │
│ write baseline load baseline │
│ __screenshots__/ __screenshots__/ │
│ btn-chromium.png btn-chromium.png │
│ │ │ │
│ ▼ ▼ │
│ test passes compare pixels │
│ match → pass │
│ diff → fail │
└─────────────────────────────────────────────────────────┘
The CI Environment Pin
┌─────────────────────────────────────────────────────────┐
│ DEVELOPER CI RUNNER │
│ macOS + retina linux + playwright container │
│ │ │ │
│ ▼ ▼ │
│ font A, scale 2 font A, scale 1 │
│ │ │ │
│ └─────────┬─────────────┘ │
│ ▼ │
│ baselines must be written │
│ in the CI container, not locally │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Screenshot matcher | toMatchScreenshot(name, opts) |
| Viewport matcher | toBeInViewport({ ratio }) |
| Requirement | Browser mode (Playwright provider) |
| Baseline location | __screenshots__/ next to the test |
| Update flag | vitest --browser -u |
| Pixel tolerance | allowedMismatchedPixelRatio |
| Region control | screenshotOptions.clip |
| Stabilizer | animations: "disabled" |
| Visibility fraction | ratio (0 to 1) |
| CI pin | Same container writes and verifies |
Key takeaways:
- Both matchers require browser mode.
toMatchScreenshotandtoBeInViewporthave no meaning in jsdom, which has no renderer and no layout engine. The Playwright provider is the prerequisite for both. - The screenshot matcher compares pixels to a committed baseline. The baseline is a binary artifact that must be regenerated intentionally with
-uand reviewed like code. TheallowedMismatchedPixelRatioabsorbs anti-aliasing noise without hiding real regressions. - The viewport matcher is a geometric check, not an occlusion check. It asserts that the element’s box intersects the viewport rectangle, optionally requiring a
ratioof the element to be visible. An element covered by a modal still passes. - Stability comes from freezing and clipping.
animations: "disabled"andcaret: "hide"remove the two most common sources of one-pixel diffs, andscreenshotOptions.clipscopes the capture to the element under test. - Baselines must be written in the environment that verifies them. A macOS baseline will not match a Linux CI runner because the fonts and the renderer differ. Pin the CI container and generate there.
Remember: Visual regression is the half of the UI contract that jsdom cannot see. The screenshot matcher compares painted pixels to a committed baseline, and the viewport matcher asserts that an element occupies visible space. Freeze animations, clip to the element, tolerate a bounded pixel ratio, and generate the baselines in the same container that CI uses. The two matchers together catch the layout and visibility bugs that DOM assertions pass straight through.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!