The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Vitest 4 performs visual regression testing in Browser Mode with the toMatchScreenshot assertion. A browser provider (such as Playwright), a deterministic test page, and a committed reference image are the essential pieces: render or navigate to the UI, capture it, review the first baseline, and let later runs compare against that image.
This guide shows a complete Vitest 4 workflow, including setup, baseline management, failure diagnosis, CI stability, comparator tuning, and an API alternative when maintaining browser infrastructure is not worthwhile.
What Vitest 4 visual regression testing does
Visual regression testing compares rendered pixels rather than only checking behavior or DOM values. It can reveal changed spacing, colors, typography, responsive layout, missing assets, and browser-rendering differences that a functional assertion may not detect.
Vitest 4 adds this capability in Browser Mode through toMatchScreenshot, as announced by the Vitest project in its Vitest 4 release announcement. The assertion can target a page or an individual element:
#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
await expect(page).toMatchScreenshot('dashboard');
await expect(page.getByRole('dialog')).toMatchScreenshot('dialog');
The first execution creates a reference image. Every later execution captures a new image and compares it with that reference.
Prerequisites and project layout
Install Vitest, a browser provider, and a browser
Browser Mode needs a provider that drives a real browser. The official visual-regression guide lists provider installation as part of setup; Playwright is a common choice.
npm install -D vitest @vitest/browser-playwright playwright
Install the browser binary required by your Playwright setup, then verify that your CI image contains the same browser version used to create baselines. Keep visual tests separate from ordinary unit tests so a unit-test run does not unexpectedly regenerate screenshots.
Use a dedicated visual-test project
A naming convention such as [name].vrt.test.ts makes the boundary obvious. You can also put tests in a visual directory and define a dedicated Vitest project for them. Run that project explicitly in local development and CI.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
src/components/button.vrt.test.ts
src/pages/dashboard.vrt.test.ts
The exact project syntax depends on your Vitest 4 configuration style. The important properties are Browser Mode enabled, a fixed browser instance, and an include pattern that selects only visual tests. Follow the provider-specific setup in the Vitest visual regression documentation when adapting the example below to your configuration.
Example Browser Mode configuration
// vitest.config.ts
import { defineConfig } from 'vitest/config';
import { playwright } from '@vitest/browser-playwright';
export default defineConfig({
test: {
projects: [
{
name: 'unit',
include: ['src/**/*.test.ts'],
exclude: ['src/**/*.vrt.test.ts'],
},
{
name: 'visual',
include: ['src/**/*.vrt.test.ts'],
browser: {
enabled: true,
provider: playwright(),
instances: [{ browser: 'chromium' }],
},
},
],
},
});
If your installed Vitest 4 release reports a configuration-shape error, use the equivalent provider and project example from the current guide rather than guessing option names. The test itself remains the same.
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
Write a visual regression test
Capture a page
Import test and expect from vitest, and page from vitest/browser. Navigate to a deterministic route, wait for the content your screenshot depends on, then assert the screenshot.
import { expect, test } from 'vitest';
import { page } from 'vitest/browser';
test('dashboard matches its approved visual', async () => {
await page.goto('/dashboard?fixture=visual');
await page.getByRole('heading', { name: 'Dashboard' }).waitFor();
await expect(page).toMatchScreenshot('dashboard');
});
Use a fixture route or seeded data instead of a live account. Disable animations in the visual-test stylesheet, freeze time where timestamps appear, and wait for fonts and asynchronous content before capturing.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteCapture one component
Element screenshots reduce noise when a full page contains unrelated dynamic regions.
import { expect, test } from 'vitest';
import { page } from 'vitest/browser';
test('error banner remains consistent', async () => {
await page.goto('/examples/errors');
const banner = page.getByRole('alert');
await banner.waitFor();
await expect(banner).toMatchScreenshot('error-banner');
});
Choose page scope for layout and responsive checks; choose element scope for a reusable component whose surrounding page is intentionally volatile.
Control screenshot options
toMatchScreenshot accepts a name or options object. The guide documents comparator settings such as a color threshold and allowedMismatchedPixelRatio. Configure them globally in vitest.config.ts or on an individual assertion when only one component needs a documented exception.
await expect(page).toMatchScreenshot({
name: 'dashboard',
threshold: 0.2,
allowedMismatchedPixelRatio: 0.01,
});
These values are illustrative configuration examples, not measured defaults or guarantees. Stabilize the environment first; increasing tolerance can hide a genuine visual defect.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
Where baselines are stored and how to update them
Review the first run
On the first run Vitest writes a reference screenshot and reports that it must be reviewed. Open the image at the expected viewport and verify content, fonts, spacing, and states before accepting it as the approved appearance.
Commit the reference images
Baselines are stored in __screenshots__ folders beside the test files. Commit them to version control so local runs and CI compare against the same artifacts. A baseline change should be reviewed like a code change: explain the intended UI change and inspect the image diff.
Remove stale files manually
Vitest does not automatically delete screenshots belonging to deleted or renamed tests. Search the relevant __screenshots__ directory and remove obsolete files deliberately; otherwise stale artifacts can confuse reviewers and repository maintenance.
Make an intentional update
- Change the UI or fixture intentionally.
- Run the visual project and inspect the reference, actual, and diff output.
- If the new appearance is correct, replace the committed baseline through your normal approved-update procedure.
- Include the baseline change in the same review as the UI change.
Diagnose a mismatch
When dimensions permit, Vitest exposes the reference image, newly captured actual image, and a diff image. Red pixels indicate changed areas. Yellow pixels indicate anti-aliasing differences when anti-aliasing is not ignored.
Read the pattern before changing tolerance
- Large shifted regions: check viewport size, device scale, responsive breakpoints, or a missing stylesheet.
- Text-only changes: verify loaded fonts, operating-system font rendering, browser version, and font fallback.
- Random small regions: look for animations, clocks, ads, network data, caret blinking, or non-seeded content.
- Entirely blank output: confirm navigation completed, the route is reachable in the test browser, and the page did not fail during startup.
- One-pixel edges: inspect anti-aliasing and only then consider a narrowly scoped comparator setting.
Do not approve a baseline merely because the diff is small. Determine whether the changed pixels represent the intended UI.
Make laptop and CI screenshots agree
Screenshot output can vary with GPU and graphics drivers, hardware acceleration, operating system, font-rendering pipeline, browser version and settings, headless versus headed mode, screen scaling, and color profile. The most reliable policy is to create and compare baselines in the same browser and platform configuration.
Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Standardize the execution image
- Pin the browser version used by the provider.
- Use the same operating-system image, fonts, viewport, and device scale factor for baseline creation and CI.
- Run headless in both environments if CI is headless.
- Use deterministic fixture data, timezone, locale, and animation behavior.
- Wait for network-dependent UI and fonts before the assertion.
When reproducing the same machine locally is impractical, the Vitest guide recommends a standardized cloud service such as Azure App Testing or a Docker container. The goal is one rendering pipeline, not a larger pixel tolerance.
Separate visual jobs from unit jobs
Run the visual project in its own CI job. This keeps browser startup and screenshot artifacts isolated, makes failures easier to triage, and prevents a unit-only change from being mistaken for a visual-test failure. Archive the reference, actual, and diff images as CI artifacts so reviewers can inspect them without rerunning the job.
Provider, environment, and assertion decisions
| Decision | Choices | When it matters |
|---|---|---|
| Browser provider | Playwright, WebdriverIO, or preview | Choose the provider that supports your browser and CI standardization requirements. |
| Execution environment | Developer machine, container, or cloud browser | Containers or cloud services help keep fonts, OS, browser, and drivers consistent. |
| Assertion scope | Element or page | Elements limit unrelated noise; pages catch layout and integration regressions. |
| Comparator | Default comparison or configured threshold and mismatch ratio | Use settings for known rendering variance only after fixing environment drift. |
| Baseline workflow | Review, commit, and deliberate update | Prevents accidental approval of regressions and stale screenshot files. |
Common errors and fixes
“Browser mode is not enabled” or provider errors
Cause: the visual project is running as a Node-only test or the provider package is missing. Fix: install the provider, enable Browser Mode for the visual project, and run the browser project rather than the unit project.
The test cannot import vitest/browser
Cause: the test is being executed outside a Browser Mode project. Fix: check the project include pattern and confirm that the browser instance is configured for that project.
Baselines differ on every CI run
Cause: environment drift or dynamic content. Fix: align OS, browser, fonts, viewport, scale, headless mode, locale, timezone, and fixture data; disable animations and wait for stable content.
A legitimate change is rejected by a tiny edge diff
Cause: anti-aliasing or a rendering-pipeline difference. First reproduce with the standardized environment. If the difference is understood and unavoidable, document a targeted threshold or mismatch ratio rather than applying a broad tolerance.
Recommended Free Tools
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
Old screenshots remain after renaming a test
Cause: Vitest does not automatically clean renamed or deleted-test images. Fix: remove the obsolete files from the adjacent __screenshots__ directory and commit the cleanup.
Or skip the browser setup
ScreenshotNeo provides a website screenshot API and MCP server. A single request can capture a URL as PNG, JPEG, WebP, or PDF, while its cleaning steps accept cookie banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers report the page verdict and billing status.
For a visual fixture or a page outside your test application, call the API directly. See the ScreenshotNeo documentation for all options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
It also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Options include full-page captures with lazy images loaded, CSS-selector element capture, dark mode, device presets or custom viewports, retina scale, PDF controls, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed image links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage reporting, and an OpenAPI specification.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteThe Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is available on every plan. Create a free ScreenshotNeo account to try it.
Recommended operating procedure
- Keep visual tests in a dedicated Vitest 4 Browser Mode project.
- Use a fixed provider, browser, viewport, OS, fonts, and fixture data.
- Capture only after the page and required elements are stable.
- Review and commit
__screenshots__baselines. - On failure, inspect reference, actual, and diff images before changing comparator settings.
- Update baselines only with an intentional UI change and code review.
Frequently Asked Questions
Can Vitest visual tests run without Browser Mode?
No. Vitest 4’s toMatchScreenshot workflow requires Browser Mode and a browser provider that supplies a real browser context.
Should I use a page screenshot or an element screenshot?
Use a page assertion for integration and layout coverage; use an element assertion when surrounding content is dynamic or irrelevant to the component under test.
Are threshold and allowedMismatchedPixelRatio measured Vitest defaults?
No. The documented values are illustrative examples. Treat them as project-specific settings after environment stabilization.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

