Lesson:Vitest Browser Mode Visual Regression Testing Guide

What is Visual Regression testing

Visual regression testing is where you take a screenshot of a page or component and save it.

Then when your tests run again in the future, it will take another screenshot and compare it to the saved one.

If they match, the test passes. If they don't match, the test fails.

This is the main and most reliable way to check for things like correct colours, CSS issues, unintended position changes, etc.

Other ways to do visual regression testing

For years I have been a huge fan of Percy.io - it is a complete system that handles your visual regression tests.

And there have always been ways to do these sorts of visual snapshots in your E2E tests without a tool like Percy.

But now with Vitest Browser Mode, which has visual regression features built in, you can do these checks quite easily without any additional systems or services.

I have caught countless bugs in my PR changes by relying on visual regression tests to catch things. (Until recently - all via Percy)

Quick example code of Visual Regression Testing

You just need to use the .toMatchScreenshot assertion function:

import { expect, test } from 'vitest';
import { page } from 'vitest/browser';

test('hero section looks correct', async () => {
  // ...the rest of the test

  // capture and compare screenshot
  await expect(page.getByTestId('hero')).toMatchScreenshot('hero-section');
});

The first time you run the test, it will take a screenshot and save it in a file next to your test file. This snapshot PNG file should be committed to git.

In this lesson

In this lesson we will cover how to set it up, how it works, and when you should use it.

Loading full lesson...

Share this lessonTweet (X) it

Invite a teammate to learn with you by sharing this lesson or dropping the link in your team chat.