QA Interview Hub · Knowledge base · Quizzes · Українська

Playwright › Emulation and environment

Visual tests: toHaveScreenshot

toHaveScreenshot compares a screenshot of a page or element with a baseline and catches visual regressions a functional test misses. The comparison is pixel-based with tolerances: threshold, maxDiffPixels, maxDiffPixelRatio. Baselines are generated and checked in one environment, usually the official Docker image, and updated deliberately in a separate commit. Changing data is stabilised, and mask is kept for unimportant areas because it hides a regression.

Playwright · Emulation

The tests are green, yet in production a button slid under the header. How do you catch that automatically?

A functional test checks that a button exists and can be clicked. It will not say that after a CSS change the button crept under the header, a font was replaced with a fallback and an icon disappeared. Visual tests exist for that: await expect(page).toHaveScreenshot() compares a screenshot with a baseline. The price: baselines have to be stored and updated, and a test easily becomes unstable if the page has anything that changes. This lesson is about how the comparison works and what to do so that it is useful rather than noisy.

How it works and why. The assertion does not just take a shot: it first waits for the page to settle. Playwright takes screenshots in a row until two consecutive ones match, and only then compares the result with the baseline. Before the shot, animations are disabled by default (animations: 'disabled': finite animations are completed, infinite ones are reset to the start), and the caret in fields is hidden (caret: 'hide'). The comparison is pixel-based: the pixelmatch library assesses the colour difference of each pixel.

What happens at toHaveScreenshot

toHaveScreenshot('card.png') shoot again and again untiltwo in a row match is there a baseline? no: write thebaseline, thetest fails yes: comparewith the baseline difference within tolerance? yes: pass no: fail + diff
Figure 1. The first run always fails: there is no baseline yet. Tolerance is set by threshold, maxDiffPixels and maxDiffPixelRatio.

Tolerance has three knobs. threshold (0.2 by default) sets how much the colour of a single pixel must differ for it to count as different. maxDiffPixels and maxDiffPixelRatio allow a certain number or share of differing pixels; by default they are zero. Globally they are set in the config:

// playwright.config.ts
export default defineConfig({
  expect: {
    toHaveScreenshot: { maxDiffPixelRatio: 0.01 },
  },
});

Baselines and the environment. Baselines live next to the test with a project and platform suffix, for example dashboard-chromium-linux.png. Fonts and rendering differ between macOS, Windows and Linux, so baselines are generated and checked in one environment, usually in the official Playwright Docker image. They are updated with npx playwright test --update-snapshots:

docker run --rm --network host --ipc=host -v $(pwd):/work -w /work \
  mcr.microsoft.com/playwright:v1.65.0-noble \
  npx playwright test --update-snapshots

The image version must match the @playwright/test version, because a browser update changes rendering too. Updating baselines is a deliberate action in a separate commit that a reviewer looks at with their own eyes. If everything is updated automatically, the test stops checking anything.

Example: a test that fails in CI, and how to stabilise it. First a naive version, with baselines generated on a Mac:

// before: the whole page, with changing content
test('statement', async ({ page }) => {
  await page.goto('/statement');
  await expect(page).toHaveScreenshot('statement.png', { fullPage: true });
});
Error: A snapshot doesn't exist at .../statement-chromium-linux.png,
writing actual.

This is a shortened output. The baseline on the Mac is named statement-chromium-darwin.png, while Linux looks for a file with the linux suffix, so all visual tests fail because of a missing baseline, not because of a pixel difference. Even with the right baseline such a test is unstable: the statement has an amount, a time and a chat widget. The fix has three steps: baselines from Docker, a component shot instead of a page, and the changing parts hidden or fixed.

// after: a component, a mask, a fixed time
test('statement card', async ({ page }) => {
  await page.clock.setFixedTime(new Date('2026-03-10T12:00:00Z'));
  await page.goto('/statement');
  await expect(page.getByTestId('summary-card')).toHaveScreenshot(
    'summary-card.png',
    {
      mask: [page.getByTestId('balance')],
      stylePath: './tests/hide-chat-widget.css',
    },
  );
});

mask paints the given elements over with a solid colour (pink by default), stylePath attaches CSS only for the duration of the shot, and setFixedTime makes the date on the page constant.

The whole page or one component

Typical

fullPage: true

A large baseline with plenty of changing content (time, ads, chat). A failure does not point to a cause, and any trifle somewhere on the page breaks the test.

Better

locator.toHaveScreenshot()

A small baseline, less noise, a clear cause of failure. Changing parts are masked or fixed through a mock or page.clock.

Figure 2. The smaller the shot area, the fewer reasons for a false failure.

Limits and alternatives. mask hides the area from regressions as well: if the layout of a masked widget breaks, the test will not say so. So it is better to make changing data stable (a mock, page.clock) and mask only what is unimportant. Pixel comparison does not answer the question "what is actually shown here": for the page structure by its ARIA tree there is toMatchAriaSnapshot, which is usually more stable than pixels but does not see visual defects. Cloud services (Percy, Chromatic, Applitools) take over storing, comparing and reviewing changes, but add a dependency and cost. Each Playwright project has its own baselines, so a mobile profile and a dark theme produce separate files.

Common mistakes.

  • Generating baselines on macOS and checking in a Linux CI: the files differ by the platform suffix, and all tests fail.
  • Shooting a whole page with ads, time and animated widgets without mask or fixed data.
  • Raising threshold or maxDiffPixelRatio until the test stops catching real changes.
  • Updating baselines "blindly" to make CI green.
  • Masking what actually needs to be checked: the test is green, and the defect stays in the mask.

Check yourself

Baselines were committed from a Mac. In a Linux CI all visual tests fail. What is the message in the log, and what to do?

Answer

"A snapshot doesn't exist … writing actual": baseline files carry a platform suffix (-darwin versus -linux), so Linux looks for different ones. Baselines are generated in the same environment where they are checked, usually in a Playwright Docker image of the same version as the package, and in a separate commit.

The page header has a live clock. Which is better: mask or page.clock.setFixedTime? What is the difference?

Answer

If the look of the clock matters, it is better to fix the time: the content is stable and a layout regression of the clock is visible. mask just covers the area, and a defect in it will never be noticed. Mask what is unimportant or cannot be fixed.

In an interview. Junior: I write visual tests with toHaveScreenshot: the first run creates a baseline, then Playwright compares with it and shows the difference. Middle/Senior: I generate baselines in Docker so there are no differences between macOS and Linux, and I review updates in a separate commit. I shoot components rather than the page, make changing data stable through mocks and page.clock, and keep mask for what is not worth checking, because it hides a regression in the masked area.

More articles in this chapter