Skip to main content

Screenshot assertions

Why This Matters

Some bugs pass every functional test. The button is there, it has the right name, clicking it works, and it is half hidden behind the footer. An icon is missing, a font did not load, a margin collapsed. A screenshot comparison catches what a user would notice at a glance, as long as you keep the noise out.

How toHaveScreenshot works

await expect(page.getByTestId("login-form")).toHaveScreenshot("login-form.png");
  1. The first time, there is no baseline: Playwright takes a screenshot and saves it as the expected image.
  2. Every run after that, it takes a new screenshot and compares it with the baseline, pixel by pixel.
  3. If they differ, the test fails and the report shows three images: expected, actual and a diff with the changes in red.

Like other web-first assertions it retries: it keeps taking screenshots until two in a row are identical and match the baseline, or the timeout runs out. That absorbs a page that is still settling. Animations are stopped and the text cursor is hidden while the screenshot is taken.

An element or the page

Screenshot an element when you care about one component: the result is small, focused and changes only when that component changes. The example repository’s tests in tests/module-6/visual.spec.ts:

test("the login form", async ({ page }) => {
  await page.goto("/login");
  await expect(page.getByTestId("login-form")).toHaveScreenshot("login-form.png");
});

test("the login form with an error", async ({ page }) => {
  await page.goto("/login");
  await expect(async () => {
    await page.getByLabel("Username").fill("practice");
    await page.getByLabel("Password", { exact: true }).fill("wrong");
    await page.getByRole("button", { name: "Log in" }).click();
    await expect(page.getByTestId("login-error")).toHaveText("Invalid username or password.", { timeout: 3000 });
  }).toPass({ timeout: 20_000 });

  await expect(page.getByTestId("login-form")).toHaveScreenshot("login-form-error.png");
});

The second test first proves the error is there, then takes the picture. Get the page into the state you want, prove it, photograph it. The toPass block around the login looks like overkill, and the first version of this test did not have it. How it got there is the story of the next lesson: two attempts at this one baseline went wrong, each for a different reason.

Screenshot the page when the layout as a whole is the risk:

await expect(page).toHaveScreenshot("login-page.png", { fullPage: true, maxDiffPixelRatio: 0.01 });

Thresholds

By default any changed pixel fails the comparison. Two options loosen that:

OptionMeaning
maxDiffPixels: 50Up to 50 pixels may differ
maxDiffPixelRatio: 0.01Up to 1% of the pixels may differ
threshold: 0.2How different a pixel’s colour may be before it counts as changed (0 to 1)

Use them sparingly. A full page has more room for harmless variation than a single form, which is why only the whole-page test above allows 1%.

Masks for what is not the point

The product card shows a photo from an image service and a price that the shop may change. Neither is what a visual test of the card is about. Mask them:

test("a product card, with the image and price masked", async ({ page }) => {
  await page.goto("/shopping");
  await expect(page.getByTestId("products-loading")).toBeHidden();
  const card = page.getByTestId(/^product-\d+$/).filter({ hasText: "Desk Lamp" });

  await expect(card).toHaveScreenshot("desk-lamp-card.png", {
    mask: [card.locator("img"), card.getByText(/^\$\d+\.\d{2}$/)],
  });
});

Masked elements are covered by a solid pink box in both the baseline and every new screenshot, so they can never cause a difference. The layout around them is still checked: if the price moves or the box changes size, the test fails. This is the real baseline:

The Desk Lamp card baseline: the photo and the price are covered by pink boxes; the name, category, rating, description and Add to Cart button are compared

Make the state deterministic

The best mask is data that never changes. The empty-shop test stubs the API (module 5), so the screenshot is identical on every run:

await page.route("**/api/shop/products**", (route) =>
  route.fulfill({ json: { items: [], page: 1, limit: 6, total: 0, totalPages: 0, priceRange: { min: 0, max: 0 } } }),
);

Real run

Making the baselines, then comparing against them:

> npm run test:visual:update
Running 5 tests using 5 workers
  ✓  1 [visual] › tests/module-6/visual.spec.ts:35:1 › the empty shop (stubbed) (3.3s)
  ✓  5 [visual] › tests/module-6/visual.spec.ts:9:1 › the login form (3.8s)
  ✓  2 [visual] › tests/module-6/visual.spec.ts:45:1 › the whole login page (3.8s)
  ✓  3 [visual] › tests/module-6/visual.spec.ts:14:1 › the login form with an error (4.1s)
  ✓  4 [visual] › tests/module-6/visual.spec.ts:24:1 › a product card, with the image and price masked (4.3s)
  5 passed (6.0s)

> npm run test:visual
  ...
  5 passed (5.1s)

The baselines end up in tests/__screenshots__/, and they are committed with the tests. Why they are made with npm run test:visual and not with a plain npx playwright test is the subject of the next lesson.

Exercise

Add a visual test for the cart’s checkout modal with one Desk Lamp in it. Mask the parts that can change without the layout changing, and decide: element or page?

Show suggested solution
test("the checkout with one product", async ({ page }) => {
  await page.goto("/shopping");
  await page.getByTestId(/^product-\d+$/).filter({ hasText: "Desk Lamp" })
    .getByRole("button", { name: "Add to Cart" }).click();
  await page.getByTestId("cart-button").click();
  const checkout = page.getByTestId("checkout-modal");
  await expect(checkout).toBeVisible();

  await expect(checkout).toHaveScreenshot("checkout-one-product.png", {
    mask: [checkout.locator("img"), checkout.getByTestId(/^cart-(line-total-\d+|subtotal|tax|total)$/)],
  });
});

An element: the modal is the component under test, and a page screenshot would also capture the shop behind it. The amounts are masked because the cart maths already has its own exact tests (modules 1 and 4); this test is about the layout. Run npm run test:visual:update once to create the baseline.