~/qa-guides/visual-regression-testing-playwright
>_ Visual Regression Testing with Playwright
A date changes on both screens. A payment button disappears on just one. Follow an unpaid order through both screenshot failures and decide what to fix or approve.
Short answer
Visual regression testing with Playwright compares how a page or component looks today with a screenshot the team has reviewed, called a baseline. Use toHaveScreenshot() after the screen reaches the state a customer would use. When a comparison fails, the expected image, actual image, and highlighted difference help you decide whether to fix the test data, report a UI defect, or approve a design change.
Consider an unpaid order. Yesterday it showed April 14 and a Pay now button. Today the screenshot differs. Did the person who created the test order use today's date? Can a shopper still pay on a narrow screen? Those questions lead to different fixes, even though Playwright reports the same kind of failure.
Set up one unpaid order at two widths
Give the test store one order that can stay unpaid across repeated runs. In this example, the order page exposes a region named Order summary. It contains the order heading, placement date, amount, payment status, and action. Capture the whole region. If the button disappears, the surrounding card still gives the reviewer something to compare.
| Input | Fixture | On screen |
|---|---|---|
| Order | Q-1042 | Order Q-1042 |
| Status | unpaid | Awaiting payment |
| Amount | 4800 cents in USD | Total $48.00 |
| Date | April 14, 2026 at noon UTC | Placed Apr 14, 2026 |
| Action | Payment available | Pay now |
Configure two Playwright projects named desktop and phone. Give them viewports of 1280 by 800 and 360 by 800 CSS pixels. For this exercise both use the same Chromium-based browser, operating system, installed fonts, light color scheme, en-US locale, UTC time zone, and device scale factor of 1. The phone project exercises the narrow layout. A shared fixture and separate reference images let you compare each layout with its own history.
Choose widths based on the part of your product that changes. A second desktop width adds little if both put the order action in exactly the same place. A width that switches to a stacked layout exercises another arrangement of the total and the button. The responsive design testing checklist covers selecting breakpoints and checking what happens between them.
Capture the first reviewed baseline
The example assumes Playwright Test, a baseURL pointing to the test store, and a seeded order at /orders/Q-1042. In tests/order.spec.ts, import test and expect from @playwright/test. Create a test named unpaid order summary with an async callback that takes { page }. Use these statements in order inside the callback.
await page.goto('/orders/Q-1042')const card = page.getByRole('region', { name: 'Order summary' })const status = card.getByText('Awaiting payment', { exact: true })await expect(status).toBeVisible()await expect(card).toHaveScreenshot('unpaid-order.png')
Here the app reveals the status after it loads the order details. A loading skeleton could sit perfectly still and produce a repeatable screenshot of the wrong screen. Pick a readiness check tied to your app's data. Keep it independent of the button whose disappearance you want the screenshot to capture. Playwright waits for consecutive captures of the locator to agree before comparing with the reference. Playwright locator screenshot assertions
On the approved build, run npx playwright test tests/order.spec.ts --update-snapshots=missing. With the default snapshot path, the named projects get distinct image files alongside the test in its snapshots directory. Open both images. Read the date and total, locate the button, and check that its label fits on the narrow card. A faithfully captured broken design will make the same defect look acceptable on every subsequent run.
Keep the reviewed files with the test. Run npx playwright test tests/order.spec.ts again against the same build and data. Both projects should match their references. Use the same rendering environment for reference generation and comparison, especially when the suite runs in CI. Playwright visual comparisons
A date changes on both screenshots
On the next run, the expected card reads Placed Apr 14, 2026. The actual card reads Placed Apr 15, 2026. In our Chrome run, Playwright counted 39 differing pixels on each card, all around the second digit of the day. The amount, status, and button look identical. The highlighted pixels tell the reviewer where to look. The stored order tells them whether the display is correct.
Inspect the order response or seed record from each run. In the example, the original placedAt was 2026-04-14T12:00:00Z. The next seed supplied 2026-04-15T12:00:00Z for the same order ID. The page formatted each value correctly. Set the fixture's creation timestamp explicitly and rerun against the original images. Both comparisons should pass with April 14 visible. Changing the browser clock alone would leave the timestamp returned by the test store untouched.
If both responses carry the original instant and the UI still changes day, keep the failure. Check which time zone the product promises for an order date and which one each browser used. A display issue around local midnight deserves a test of its own. Masking the date in the screenshot would remove the evidence you need to distinguish those cases.
A payment button disappears on the phone
Keep the April 14 order and introduce a narrow-screen CSS rule that sets the payment button's visibility to hidden at widths up to 600 pixels. On desktop the approved card still matches. On the phone the expected image has Pay now beneath the total. The actual image has a blank patch in its place. The card keeps its original height because the hidden button still occupies space.
Compare the actual image with the full expected card before interpreting the colored diff. The unpaid status and $48.00 total establish that payment should be available. In the narrow browser, inspect the button's computed visibility. Try widths of 600 and 601 pixels to isolate the rule. The control is hidden at 600 and visible at 601. A screenshot of the button alone could time out while waiting for the hidden element. The parent card captures what the shopper sees around it.
Keep the phone reference and attach the three images to the defect with the order ID, viewport, and affected build. Remove the faulty rule and rerun both projects. The repaired phone should match its original reference. A desktop-only run would miss both the failure and the evidence that the repair worked.
Check that a matching button also works
A second test can use the same unpaid fixture to answer a different question. Find the Pay now button in the summary by role, click it, and check that a heading named Payment review becomes visible. In this exercise the click opens a local review screen and the order stays unpaid, so each run can reuse the starting state.
Run the interaction test independently of the screenshot assertion. A screenshot failure ends its test at that assertion. These separate results show what the shopper could still do on the 360-pixel layout.
| Change | Image | Click |
|---|---|---|
| New date | Date differs | Review opens |
| Hidden | Button missing | No visible button |
| No handler | Matches | Stays on order |
To reproduce the last row, disconnect the click handler and leave the markup and styling in place. In our run both screenshots matched. The interaction test timed out waiting for the destination heading. If a checkout change also touches order creation or totals, the regression testing checklist can help select the other workflows to rerun.
Decide whether a pixel tolerance is safe
threshold controls how far apart two pixel colors can be before the comparison counts a difference. maxDiffPixels sets an allowance for the number of differing pixels. maxDiffPixelRatio expresses that allowance as a share of the whole image. Increasing any of them to quiet a noisy run changes what future defects the test can catch.
Take a screenshot of the entire 360 by 800 viewport in this fixture. At one image pixel per CSS pixel, it contains 288,000 pixels. A ratio of 0.02 allows 5,760 differing pixels. The button occupies a rectangle of 110 by 36 pixels, or 3,960 pixels. Hiding it leaves the rest of the layout in place. Playwright counted 3,463 differing pixels in this run. The default comparison failed. With the 2% allowance, the same screenshot passed with the payment button missing.
Try the missing-button case against any proposed tolerance. The comparison needs to fail while the button is hidden and pass after the fix. Capturing the relevant region also makes a small change easier for a human to locate. If an unrelated widget keeps changing, see whether selecting a more useful region or supplying repeatable data removes the noise at its source.
Update a baseline for an intentional change
Suppose an approved design gives only the phone payment button a blue fill and rounder corners. Run the existing tests first. The phone diff should follow the button's outline and fill, the label should remain readable, and the interaction test should reach payment review. Check the actual image for a second change, such as a shifted total, before accepting the new design.
For the example's one named screenshot in one test, run npx playwright test tests/order.spec.ts --project=phone -g "unpaid order summary" --update-snapshots=changed. Inspect the changed files. The phone reference should contain the approved style and the desktop reference should be identical to its previous version. Include the design decision and the new image in review so someone else can check the same boundary.
Finally, run both projects against the approved change with npx playwright test tests/order.spec.ts --update-snapshots=none. This run compares against the references you intend to keep. If a reviewer spots another difference, the previous reference in version control and the saved actual and diff images preserve the evidence from before the update.
FAQ
Start with the error message. If a reference is missing, inspect the expected file path, project name, platform, and files checked into version control. If a reference exists and the diff traces the edges of text all over the card, compare browser versions, operating system images, and installed fonts. Reproduce the run in the environment that owns the baseline before approving any new images.
A locator screenshot requires a region it can capture. If the region is missing, the readiness check or the capture can time out before a visual comparison takes place. Look at the page state or a wider diagnostic screenshot. An unexpected sign-in screen, an unavailable order, and a card with a changed accessible name each call for a different fix.
A mask covers the selected element's bounding box during capture. It can be useful for a rotating avatar when the surrounding layout is the subject of the check. A changing box can still move its neighbors. Keep its size predictable and verify that the selector matches only the intended element, especially on the narrow layout.
Create a separate named screenshot for the focused state. Reach the action with the keyboard, check which element has focus, and capture a region large enough to include the entire focus indicator. Leave space around the button in the capture. A tight crop can cut off an outline drawn outside its border.