QA and Test Automation ยท Lab 17 of 35

Visual Regression Testing With Playwright Screenshots: Lab

Add screenshot tests to ShopRung: a strict config, a page, a card, the header and a phone layout. Create baselines, prove they are stable, catch a one-line CSS change (185 pixels), read the diff, and update baselines the safe way.

โฑ 40 minIntermediate๐Ÿ’ธ Free6 steps

Node.js 22Playwright Test 1.63TypeScriptShopRung

Overview video

1 / 6

0 of 6 steps done

What you will build

A Playwright project with 4 visual tests and their approved baseline images:

  • The product grid, with the result count masked.
  • One product card, the Testing Field Guide: a small element screenshot, where a small change is a big share of the pixels.
  • The header with the search box and cart link.
  • The home page at phone size (390 ร— 844).

You also learn the workflow around them: why the first run fails, how to read a diff, and when to update a baseline.

Before you start

Setup

S1Start ShopRung

Start ShopRung as in lab 1 with npm start, and leave it running.

Run
curl http://localhost:8080/api/health
You should see
{"status":"UP","app":"ShopRung","version":"1.0.0"}

S2Create the project folder

Make a folder shoprung-visual, add the files from step 1, and install.

Run
mkdir shoprung-visual
cd shoprung-visual
# add package.json, .gitignore and playwright.config.ts from step 1, then:
npm install
npx playwright install chromium
1

A config built for stable screenshots

One viewport, no animations, no blinking cursor, and a strict default tolerance.

Most visual testing pain is false failures: something changed that nobody cares about. The config removes the usual causes before you write a test:

  • A fixed viewport of 1280 ร— 800, so screenshots are the same size on every machine.
  • animations: 'disabled' freezes CSS animations and transitions at their end state.
  • caret: 'hide' hides the blinking text cursor.
  • maxDiffPixels: 0 is strict on purpose. Step 6 explains why loose tolerances are dangerous.
package.json
{
  "name": "shoprung-visual",
  "private": true,
  "scripts": {
    "test": "playwright test",
    "report": "playwright show-report"
  },
  "devDependencies": {
    "@playwright/test": "1.63.0"
  }
}
.gitignore
node_modules/
playwright/.auth/
test-results/
playwright-report/
  1. Diffs and actual images from failed runs. The baselines live next to the tests and DO go into Git.line 3
playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  workers: 1,
  reporter: [['list'], ['html', { open: 'never' }]],
  expect: {
    toHaveScreenshot: {
      animations: 'disabled', // freeze CSS animations and transitions
      caret: 'hide',          // no blinking text cursor
      maxDiffPixels: 0,       // strict: one changed pixel fails (see step 6)
    },
  },
  use: {
    baseURL: process.env.BASE_URL ?? 'http://localhost:8080',
    viewport: { width: 1280, height: 800 }, // the same size on every machine
  },
  projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'], viewport: { width: 1280, height: 800 } } }],
});
  1. A half-finished animation is the classic flaky screenshot.line 9
  2. Every pixel counts. Loosen per test only with a reason.line 11
  3. Set on the project too, so the device preset does not override it.line 18
2

The first screenshot test

A screenshot of the product grid, and the baseline it creates.

Create tests/visual.spec.ts. Two habits make screenshots stable: reset the data before each test (same prices, same stock), and wait until the page is complete before taking the picture (all 12 cards). Then toHaveScreenshot compares the main area with a stored image. The result count is masked: that part is covered with a box and not compared.

Run it. The first run fails on purpose: there is no baseline yet, so Playwright writes the screenshot it took and tells you so. Open tests/visual.spec.ts-snapshots/product-grid-chromium-linux.png (the name ends with your system, -darwin on a Mac, -win32 on Windows) and look at it: this image becomes the truth that future runs are compared with. Then run again: it passes.

tests/visual.spec.ts
import { test, expect } from '@playwright/test';

test.beforeEach(async ({ request }) => {
  await request.post('/api/test/reset'); // fixed data: same stock, same prices
});

test('product grid', async ({ page }) => {
  await page.goto('/');
  await expect(page.getByTestId('product-card')).toHaveCount(12); // wait until the page is complete
  await expect(page.locator('main')).toHaveScreenshot('product-grid.png', {
    mask: [page.getByTestId('result-count')], // a part we choose not to compare
  });
});
  1. Fixed data. A stock count that changes would change the picture.line 4
  2. Wait for the full page. A screenshot of a half-loaded page is a flaky test.line 9
  3. Masked areas are painted over in both images.line 11
Run
npx playwright test
npx playwright test
You should seeyour text will differ: the model writes it
    Error: A snapshot doesn't exist at .../tests/visual.spec.ts-snapshots/product-grid-chromium-linux.png, writing actual.
  1 failed

  1 passed (1.1s)
Stuck on this step?
The second run fails too, with a few pixels different.
Something on the page still moves or loads late. Check the reset ran and that you wait for all 12 cards. Fonts loading late can also do this: run once more and compare the diff.
3

An element, the header and a phone

Three more screenshots at different sizes, created with --update-snapshots.

Replace tests/visual.spec.ts with the full version. Three new tests:

  • One product card. An element screenshot of just the Testing Field Guide card. Small screenshots are better at catching small changes, because one wrong price is a big part of a small image.
  • The header. Shared parts that appear on every page are worth one screenshot each.
  • The phone layout. setViewportSize makes the page 390 ร— 844, so you check the responsive layout. toHaveScreenshot on the page captures the visible screen.

This time create all baselines in one go with --update-snapshots, then run normally twice. Two green runs in a row show the screenshots are stable.

tests/visual.spec.ts 10 new or changed lines
import { test, expect } from '@playwright/test';

test.beforeEach(async ({ request }) => {
  await request.post('/api/test/reset'); // fixed data: same stock, same prices
});

test('product grid', async ({ page }) => {
  await page.goto('/');
  await expect(page.getByTestId('product-card')).toHaveCount(12); // wait until the page is complete
  await expect(page.locator('main')).toHaveScreenshot('product-grid.png', {
    mask: [page.getByTestId('result-count')], // a part we choose not to compare
  });
});

test('one product card', async ({ page }) => {
  await page.goto('/');
  const card = page.getByTestId('product-card').filter({ hasText: 'Testing Field Guide' });
  await expect(card).toHaveScreenshot('card-testing-field-guide.png');
});

test('header and search', async ({ page }) => {
  await page.goto('/');
  await expect(page.getByTestId('product-card')).toHaveCount(12);
  await expect(page.locator('header')).toHaveScreenshot('header.png');
});

test('product grid on a phone', async ({ page }) => {
  await page.setViewportSize({ width: 390, height: 844 });
  await page.goto('/');
  await expect(page.getByTestId('product-card')).toHaveCount(12);
  await expect(page).toHaveScreenshot('home-phone.png');
});
  1. One card, found by its content.line 17
  2. The shared header: if it breaks, it breaks everywhere.line 24
  3. A phone-sized viewport for the responsive layout.line 28
Run
npx playwright test --update-snapshots
npx playwright test
npx playwright test
You should seeyour text will differ: the model writes it
  4 passed (2.2s)
  4 passed (2.2s)
  4 passed (2.1s)
4

Catch a change you did not assert

A one-line CSS change fails the card test, and the diff image shows where.

Pretend a developer changed a style. Add this line as the first line of the one product card test, just before const card = ...:

  await page.addStyleTag({ content: '.price { color: red }' }); // TEMPORARY: pretend a developer changed the CSS

Run the suite. The card test fails: 185 pixels are different, the price text. No test ever asserted the price colour, yet the screenshot caught it. Playwright saves three images in test-results/: expected (the baseline), actual (this run) and diff (changes in red). Open the HTML report with npx playwright show-report: the failed test has an image comparison with a slider.

Then remove the line again and run once more: 4 passed.

Run
npx playwright test
You should see
  1) [chromium] โ€บ tests/visual.spec.ts:15:5 โ€บ one product card

    Error: expect(locator).toHaveScreenshot(expected) failed

      185 pixels (ratio 0.01 of all image pixels) are different.

    Expected: tests/visual.spec.ts-snapshots/card-testing-field-guide-chromium-linux.png
    Received: test-results/visual-one-product-card-chromium/card-testing-field-guide-actual.png
    Diff:     test-results/visual-one-product-card-chromium/card-testing-field-guide-diff.png

  1 failed
  3 passed (3.0s)
5

When a change is intended: update and review

The safe way to accept a visual change.

Sometimes the change is right: a redesign, a new font. Then you update the baseline. Do it for one test, after looking at the diff, never for everything at once:

-g "one product card" limits the update to that test. Then git diff --stat shows which PNG files changed, and in a pull request the reviewers see the old and new images side by side. The rule teams use: the new baseline goes in the same pull request as the code change that caused it.

Run
npx playwright test -g "one product card" --update-snapshots
git status --short
You should seeyour text will differ: the model writes it
 M tests/visual.spec.ts-snapshots/card-testing-field-guide-chromium-linux.png
Why this way? Running --update-snapshots on everything to make CI green turns visual tests into a rubber stamp. The diff exists so a person decides.
6

Tolerances, and where baselines are made

Know when to loosen a tolerance, and why CI must make its own baselines.

Tolerances. maxDiffPixels and maxDiffPixelRatio let a few pixels differ. They exist for real rendering noise, but they also hide real bugs. The CSS change above was 185 pixels of a 240 ร— 174 card, under half a percent. A maxDiffPixelRatio of 0.01 would have passed it. Keep the strict default; loosen one test only when you have seen noise you cannot remove.

Where baselines come from. Fonts render differently on macOS, Windows and Linux, which is why the file names end in -darwin, -win32 or -linux. CI usually runs Linux, so baselines made on your Mac will not match. Create and update them in the same Linux image CI uses, for example Playwright's official Docker image, with your project folder mounted:

docker run --rm --network host -v "$PWD":/work -w /work mcr.microsoft.com/playwright:v1.63.0-noble \
  npx playwright test --update-snapshots

On macOS and Windows, Docker cannot reach localhost with --network host; use -e BASE_URL=http://host.docker.internal:8080 instead.

Check it works

Your suite works when all three are true:

  • Stable: two normal runs in a row both show 4 passed, with no changes in between.
  • Sensitive: the one-line CSS change from step 4 fails the card test, and the diff shows the price.
  • Reviewable: your baseline PNGs are in the project and you have looked at every one of them.
Test
npx playwright test
npx playwright test
You should see
  4 passed (2.2s)
  4 passed (2.1s)

Troubleshooting

Every test fails with "A snapshot doesn't exist".

Normal on the first run, or on a new operating system: the baselines for this system do not exist yet. Run once with --update-snapshots and look at the images.

Tests pass on your Mac and fail in CI.

Different fonts. Make baselines in the CI image (step 6), not on your laptop.

A few pixels differ on every run.

Something is not deterministic: a date, a counter, an image loading late, an animation. Mask it, wait for it, or reset its data.

The phone screenshot is cut off or too long.

toHaveScreenshot on the page captures the visible screen. Add { fullPage: true } only if you really want the whole scroll height; it makes bigger, slower diffs.

What changes in production

  • Teams screenshot key pages and shared components (header, buttons, forms) rather than every state of every page, because every baseline needs care.
  • Baselines are created and updated in the same Docker image as CI, and reviewed as image diffs in pull requests.
  • Hosted visual testing services add review dashboards, many browsers and smarter diffing; Playwright's built-in comparison is enough for many teams.
  • Component libraries are often tested visually one component at a time in Storybook, which keeps screenshots small and stable.

Interview angle

โ€œHow do you keep visual tests from being flaky?โ€

Fixed data and a fixed viewport, waiting until the page is complete, animations disabled, the caret hidden, and dynamic parts masked. Baselines are made and updated in the same Linux image CI uses, never on laptops. I keep tolerances strict because a small pixel count can be a real bug, prefer element screenshots of key components, and only update a baseline after looking at the diff, in the same pull request as the change.

Clean up

The full project

Every file from this lab, as it is after the last step.

Download TypeScript project (.zip)