Skip to content

    Frontend System Design

    Visual Regression Testing

    Catch layout and style regressions that DOM assertions miss: how screenshot comparison works, how to make it deterministic, and how to review the diffs.

    By Published 13 min read

    • frontend-system-design
    • visual-testing
    • testing
    • screenshots
    Share

    Standard lessonintermediateFrontend System Design

    Before this: Unit and Component Testing

    What you'll learn: By the end of this lesson you will be able to say what a visual regression test catches that a DOM assertion does not, explain how a screenshot is compared with a baseline (pixel difference, a colour threshold, an allowed number of different pixels), list the main causes of false failures and how to remove each, describe the review workflow for a failing diff, and decide what is worth screenshotting. No lab accompanies this lesson: the tool configuration is shown as code that is not run here.

    Think of a shop owner who photographs the window every night from the same spot. Next morning they lay the new photo over the old one. If a poster fell down, it shows at once. If the sun was lower today, the photo also differs, and that is not a fault. The whole practice is two skills: take the photo the same way every time, and decide what a difference means.

    The running example is the product page of the ShopStream storefront: a title, an image, a price, a button from the shared component library, and a responsive grid below. A change to a shared stylesheet can move any of it.

    The core idea

    1. A visual test compares what the user sees. It renders a page or component in a real browser, takes a screenshot, and compares it with an approved earlier screenshot called a baseline.
    2. It finds a different class of bug. A test that asserts the button exists and is enabled passes when a CSS change pushes the button off screen. The screenshot does not.
    3. The hard part is not the comparison, it is determinism. The same page must render the same pixels on every run. Most effort goes into removing noise (fonts, animation, dates, data, machines) so that a failure means something.

    Three illustrations run through the lesson: a minimal example (one screenshot assertion), a realistic example (the product page with a masked, changing area) and a failure example (baselines made on one machine and checked on another).

    What the test does

    Figure 1. The life of one visual check

    A visual test renders a page, captures it, compares it with the stored baseline and either passes or produces a diff to reviewPage or component to Screenshot (render); Screenshot to Compare (capture); Baseline to Compare (read); Compare to Diff for review (if different)Page or component: fixed dataPage orcomponentfixed dataScreenshot: same environmentScreenshotsame environmentCompare: threshold, pixel countComparethreshold, pixelcountBaseline: approved imageBaselineapproved imageDiff for review: report artifactDiff forreviewreport artifactrendercapturereadif different

    How to read this: the baseline is a stored file, so the comparison is only as good as the match between the environment that made it and the one that checks it.

    On the first run there is no baseline. Playwright's documentation says that on first execution it generates reference screenshots, and that subsequent runs compare against them. Its toHaveScreenshot also takes screenshots until two consecutive ones match before saving the last, which absorbs some instability while the page settles. Snapshots live next to the test in a directory the docs say to commit to version control, and you refresh them with npx playwright test --update-snapshots when the page has changed on purpose. The file names carry the browser and platform, for example example-test-1-chromium-darwin.png, so a baseline made on one operating system is not silently reused on another.

    How two images are compared

    Comparison tools count the pixels that differ. The pixelmatch library "compares two images, writes the output diff and returns the number of mismatched pixels". All images need the same dimensions, so a size change is itself a failure. Its threshold (default 0.1) is a per-pixel perceptual colour difference where 1 is the difference between black and white, so lower is more sensitive. It also detects anti-aliased pixels, the soft edges of text and curves, and ignores them unless includeAA is set.

    Playwright exposes the same ideas as options of toHaveScreenshot. Its threshold is "an acceptable perceived color difference in the YIQ color space between the same pixel in compared images", between 0 (strict) and 1 (lax), and defaults to 0.2. maxDiffPixels is the acceptable number of different pixels, and maxDiffPixelRatio the acceptable ratio. Defaults for those two are configurable in the config file, and the docs say maxDiffPixels is unset by default.

    Option What it controls Too strict Too loose
    Colour threshold How different one pixel's colour must be to count Font smoothing noise fails the suite A slightly wrong brand colour passes
    maxDiffPixels How many pixels may differ One moved icon is not allowed even if intended A small button changing can hide inside the allowance
    maxDiffPixelRatio The same, as a share of the image Same as above A large page hides a large defect

    An illustrative calculation (arithmetic, not a measurement): a 1280 by 720 screenshot has 921,600 pixels. An allowance of 0.01 percent of the pixels would be about 92 pixels, which is roughly a 9 by 10 pixel block, enough for a small icon to change colour and pass. Allowances should be as small as the environment's own noise permits, and set per test, not once for everything.

    Making screenshots repeatable

    Every false failure comes from something other than the change being tested. The sources, and what to do about each:

    Figure 2. Where noise comes from and how to remove it

    flowchart LR accTitle: Sources of noise in screenshots accDescr: Five sources of noise lead to five fixes. Different machines and operating systems are fixed by running in one pinned environment. Animations and carets are fixed by disabling them. Fonts that load late are fixed by waiting for them. Dates, random values and live data are fixed by masking or fixing them. Hover states are fixed by moving the pointer away. A["Different machine
    or OS"] --> A2["Run baselines and checks
    in one pinned environment"] B["Animation, caret"] --> B2["Disable animation,
    hide caret"] C["Fonts loading late"] --> C2["Wait for fonts,
    self-host them"] D["Dates, random,
    live data"] --> D2["Fix the data, or
    mask the area"] E["Hover, focus"] --> E2["Move the pointer away,
    set focus on purpose"]

    How to read this: left is what makes two runs differ, right is the standard answer. A flaky visual test almost always has one of the five on the left.

    • Environment. Playwright's documentation says browser rendering "can vary based on the host OS, version, settings, hardware, power source (battery vs. power adapter), headless mode, and other factors", and that for consistent screenshots you should run tests in the same environment where the baseline screenshots were generated. A common way is a pinned container image: Playwright publishes mcr.microsoft.com/playwright:<tag> images that bundle the browsers and their system dependencies, and its docs recommend pinning the image to a specific version. The Playwright package itself is installed separately and must match the image version, or the browsers will not be found.
    • Animation and the caret. In toHaveScreenshot, animations defaults to "disabled" (it stops CSS animations, CSS transitions and Web Animations) and caret defaults to "hide". Those defaults help; do not turn them off without a reason.
    • Fonts. A page captured before its web fonts load shows the fallback font. The promise document.fonts.ready resolves once the document has finished loading fonts and no further font loads are needed. Self-hosted fonts make this deterministic: see Image and Font Optimization.
    • Dynamic content. Fix the data (the same fixture on every run, which is why this lesson's sibling on network mocking matters), or hide the volatile area. mask takes locators to cover with a coloured box (default #FF00FF), and stylePath applies a stylesheet during capture, for example to hide an iframe.
    • Hover and focus. The Playwright docs advise moving the mouse off interactive elements first, for example page.mouse.move(-1, -1).

    What to screenshot

    A visual test is an expensive assertion: reviews are by eye and every intended design change updates files. Spend it where pixels are the contract.

    Target Good fit Why
    A component in isolation, in each state Yes Small, stable inputs; a failure names one component. Storybook's docs describe visual tests as snapshots of every story compared with baselines
    A few key full pages at fixed widths Yes Catches layout and cascade problems between components
    Every page at every width in every browser No Cost grows by multiplication, so noise and review time follow
    Logic, copy and accessibility No A unit, component or accessibility test checks those more cheaply and precisely

    Storybook's page also contrasts visual tests with markup snapshots: HTML snapshots can produce more false positives, because code changes do not always change what the user sees. See Modern CSS Layout and Responsive Design for the widths worth fixing and CSS Architecture and Scaling for why a shared style change can reach so far.

    Reviewing a failing diff

    Figure 3. Triage of a failed visual check

    flowchart TD accTitle: Triage of a failed visual check accDescr: When a visual check fails, open the diff. If the change is intended, update the baseline and review the new image in the pull request. If it is a real regression, fix the code. If it is noise, find its source: environment, animation, fonts, data or hover, fix that, and do not raise the threshold first. F["Visual check failed"] --> D{"Open the diff:
    what changed?"} D -->|"intended"| U["Update baseline,
    review new image in the PR"] D -->|"a real defect"| X["Fix the code"] D -->|"nothing you changed"| N["Find the noise source,
    fix it, then re-run"] N -.->|"last resort"| T["Raise the allowance
    for this test only"]

    How to read this: the order matters. Raising a threshold to make a failure disappear should come last, because it also hides real regressions of the same size.

    The review is the point: a baseline update is a changed image in a pull request, and a human must look at it. Storybook's workflow shows the same loop: inspect the pixel diffs, accept intended changes as new baselines, and fix and rerun for unintended ones. Attach the diff image to the failing CI run and require a reviewer for any change under the snapshots directory.

    Illustration 1 (minimal example): one assertion

    Nothing in this lesson was run: no browser is automated on the course author's machine, and screenshot tests run in CI. What follows is configuration and test code in the shape the Playwright documentation shows, not output.

    // playwright.config.ts (the expect block follows the docs' sample)
    import { defineConfig } from "@playwright/test";
    
    export default defineConfig({
      expect: {
        toHaveScreenshot: {
          // An acceptable amount of pixels that could be different, unset by default.
          maxDiffPixels: 10,
        },
      },
    });
    // product-page.visual.spec.ts
    import { test, expect } from "@playwright/test";
    
    test("product page matches its baseline", async ({ page }) => {
      await page.goto("/products/p-100");
      await page.evaluate(() => document.fonts.ready);
      await expect(page).toHaveScreenshot("product-page.png");
    });

    The first run would write product-page.png as the baseline, and later runs would compare against it. The page is assumed to be served with fixed data; the config line allows up to ten different pixels. Where the value 10 came from is the docs' sample, not a recommendation.

    Illustration 2 (realistic example): the product page with a changing area

    The product page shows a "Deal ends in" countdown and a recommendations strip that changes by user. Both would differ on every run. The test fixes the recommendations with the same fixture each time and masks the countdown, so the rest of the page is still compared:

    test("product page, desktop width", async ({ page }) => {
      await page.setViewportSize({ width: 1280, height: 720 });
      await page.goto("/products/p-100");
      await page.evaluate(() => document.fonts.ready);
      await page.mouse.move(-1, -1);
      await expect(page).toHaveScreenshot("product-desktop.png", {
        mask: [page.getByTestId("deal-countdown")],
        fullPage: true,
      });
    });

    mask and fullPage are options of toHaveScreenshot: the first covers matching elements with a coloured box, the second captures the full scrollable page instead of the viewport. A matching test would exist for a narrow width. The masked region is not tested, so a defect inside the countdown is invisible to this check, and a separate component test covers its logic.

    Illustration 3 (failure example): baselines made on a laptop

    A developer generates baselines on a laptop and pushes. CI runs the tests on a Linux runner and every screenshot fails, because text smoothing and font rendering differ between the two machines. The Playwright docs say screenshots differ across browsers and platforms because of different rendering and fonts, and snapshot names carry the platform. The fix is not a higher threshold. Generate and check baselines in the same pinned image, and treat a laptop run as a preview only.

    Choosing

    Choice Gain Cost
    Self-run screenshots in CI Full control, no third party You own environment pinning and the review UI
    A hosted visual service Review UI, shared baselines A dependency, and screenshots leave your network
    Component-level visual tests Small, stable, named failures Does not catch problems that appear only when components combine
    Page-level visual tests Catches interactions between components Larger images and more noise from data and layout
    Strict thresholds Small regressions found More false failures and more review time

    Build it: no lab, tool configuration only

    There is no lab for this lesson. A visual test needs a real browser, and the course's rule is that browser automation runs only in CI (GitHub Actions), never on the author's machine. Anything shown above is configuration you do not run here, and the lesson shows no screenshots or diff output because none were produced.

    The behaviours described above come from the Playwright, pixelmatch, MDN and Storybook pages listed below; check them against the version you install.

    A CI job would run the tests in a pinned image. This sketch follows the docs' image name pattern; replace the placeholder with the exact version that matches your installed Playwright package:

    # .github/workflows/visual.yml (sketch, not run here)
    jobs:
      visual:
        runs-on: ubuntu-latest
        container: mcr.microsoft.com/playwright:<playwright-version>-noble
        steps:
          - uses: actions/checkout@v4
          - run: npm ci
          - run: npx playwright test --project=chromium

    In practice: a shared style change that moved every button

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A design system team changes the base padding of the shared button. Unit and component tests all pass, because buttons still render and click. In several product screens the button now wraps its label onto two lines, and on narrow widths it pushes the price out of view.

    Starting architecture

    Figure 4. Starting point: tests check behaviour, nothing checks appearance

    Starting architecture: a shared style change reaches many screens, and only behaviour tests guard themDesign system to Product page (styles); Design system to Cart page (styles); Product page to CI (behaviour); Cart page to CI (behaviour)Design system: shared button styleDesign systemshared buttonstyleProduct page: uses buttonProduct pageuses buttonCart page: uses buttonCart pageuses buttonCI: unit tests onlyCIunit tests onlystylesstylesbehaviourbehaviour

    How to read this: the shared style reaches both pages, and CI looks only at behaviour, so nothing connects the change to what it did to the layout.

    Options considered

    Option What it fixes What it costs Risk
    Visual tests of the design system's components Each component state is checked on its own Baselines to maintain; one environment to pin Does not catch combinations in real pages
    Visual tests of the design system plus a few key pages Both levels covered More images, more review Noise if data and fonts are not fixed

    The decision

    Field Decision record
    Context A shared style change can alter many screens, and behaviour tests cannot see appearance.
    Decision Add visual tests for each component state in the library, plus the product and cart pages at two widths, all run in one pinned container in CI. Fixed data, animations off, fonts awaited, volatile areas masked.
    Consequences, good A padding change fails with a diff that shows exactly which screens moved.
    Consequences, bad Baselines to review on every intended design change, and a pinned image to keep current.
    Revisit when The number of baselines makes review slow, or a hosted service would carry the review load more cheaply.

    Rollout and verification

    1. Start with a few high-value pages and component states, not every screen.
    2. Run the suite several times on an unchanged build and fix any test that fails without a change. A test that fails by itself is noise, not coverage.
    3. Make it blocking only after the noise is gone, and require a reviewer on any snapshot change.

    The 2 a.m. failure

    After the suite goes blocking, a release is stuck because a visual test fails on every run and nobody changed the page. The diff shows a tiny shift in text on one screen. The cause is a font that finishes loading after the screenshot (illustrative), so the fallback font appears in the capture.

    First three checks: (1) open the diff and see which pixels moved; (2) rerun on the previous commit to see if the failure predates the change; (3) check whether the test waits for fonts. Mitigation: add the font wait, regenerate that baseline in the pinned image and review it. Follow-up: run new visual tests several times before merging them, and keep one owner for the pinned image and snapshot review.

    Architect's notes

    • Make it deterministic before making it strict. Fix data, fonts, animation and the environment first.
    • One environment for baselines and checks. Laptop screenshots are previews.
    • Mask what you cannot fix, and test it another way.
    • Keep allowances small and per test. A global loose threshold hides real defects.
    • Treat a snapshot change like a code change. Someone looks at the image.

    Common mistakes

    • Baselines made on a different machine from the one that checks them.
    • Raising the threshold to silence flakiness instead of removing its cause.
    • Live data on screen, so the image changes on every run.
    • Accepting updated baselines without looking.

    Key takeaways

    • A visual test compares rendered pixels with an approved baseline and finds regressions that DOM assertions cannot.
    • Comparison uses a colour threshold and a count or ratio of different pixels; images must be the same size.
    • Most failures are noise: fix the environment, animation, fonts, data and hover first.
    • Screenshot components in each state and a few key pages, not everything.
    • A baseline update is a reviewed image change, never an automatic one.
    • Raise an allowance last, and for one test only.

    Practice exercises

    Exercise 1 — Starter (45 min): Pick one page of your own app. List every source of noise from Figure 2 that could appear on it, and say how you would remove each.

    Exercise 2 — Intermediate (2 hours): Write the test and config for two widths of one page, with volatile areas masked, and note what you expect the first CI run to do.

    Exercise 3 — Advanced (half day): Design a review process for baseline changes: who approves, and what happens when a design system change touches fifty baselines.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments