Cypress 22 ๐ฒ Visual Testing โ Image Snapshots and Percy Integration
Visual testing catches the bugs that functional tests miss: a button that shifted four pixels to the left, a font that failed to load, a z-index fix that pushed the modal behind the overlay, a color token that changed in the design system and broke every card on the page. Functional assertions check behavior; visual assertions check appearance. Cypress is not a screenshot-diffing engine by itself, so visual testing in a Cypress project is always a pairing: Cypress drives the browser and captures the screenshot, and a separate tool compares it against a baseline. This chapter covers the two dominant pairings โ cypress-image-snapshot for local, committed baseline snapshots, and Percy for cloud-hosted, cross-browser visual reviews inside CI.
The chapter walks through how each tool captures and compares images, where the baselines live, how the comparison tolerates anti-aliasing and font-rendering noise, and what happens in CI when a diff is detected. It also covers the decision between the two approaches and the pitfalls that make visual suites flaky when the environment is not pinned.
Key point: Visual testing is a two-part pipeline: Cypress captures the screenshot, and a comparator diffs it against a stored baseline. cypress-image-snapshot stores baselines in the repo and fails the test on a pixel diff beyond a threshold; Percy uploads the snapshot to a cloud project and renders it across browsers and widths, where a human reviews the diff before it can block a merge.
Why visual testing exists
The functional test blind spot. A functional test asserts that the checkout button exists and that clicking it fires the right request. It says nothing about whether the button is visible, whether its label is clipped, or whether the sticky header covers it on a 375px viewport. Visual regressions are exactly the class of bug that DOM assertions cannot see, and they ship silently.
The CSS is the code nobody tests. A design system token change, a dependency upgrade that alters a flexbox default, or a global stylesheet edit can restyle hundreds of components with a green test suite. Visual testing treats rendered pixels as the assertion target, so a style regression fails a test the same way a logic regression does.
The manual QA cost. Reviewing every page after every release is expensive and inconsistent โ two reviewers notice different things. A stored baseline makes the comparison mechanical: the screenshot either matches or it does not, and the diff image shows exactly where.
The cross-browser problem. A layout can be perfect in Chromium and broken in WebKit. Percy exists largely because rendering a snapshot in multiple browsers and viewport widths is a matrix problem that is painful to run locally, and the cloud service does the matrix in parallel.
The trade-off. Visual tests are the most environment-sensitive tests in a suite. Font rendering, GPU anti-aliasing, OS-level subpixel rendering, and device pixel ratio all change pixels without changing the page. A visual suite is only as stable as the environment is pinned, which is why baselines must be generated in the same container the CI uses.
a. How cypress-image-snapshot captures and compares
cypress-image-snapshot extends Cypress with a matchImageSnapshot command. The first run writes a baseline PNG into the snapshots directory; subsequent runs compare the fresh screenshot against that baseline and fail the test if the difference exceeds the threshold.
The install is a dev dependency plus two lines of setup โ a command import in the support file and the plugin registration.
// cypress/support/commands.ts
import { addMatchImageSnapshotCommand } from "cypress-image-snapshot/command";
// Register the cy.matchImageSnapshot() command with project defaults
addMatchImageSnapshotCommand({
failureThreshold: 0.01, // 1% of pixels may differ before failing
failureThresholdType: "percent",
customDiffConfig: { threshold: 0.1 }, // per-pixel color tolerance (0โ1)
});
The plugin registration is what wires the Node-side comparison into the browser-side command. The addMatchImageSnapshotPlugin call in cypress.config.ts receives the screenshot buffer and does the diffing on disk.
// cypress.config.ts
import { defineConfig } from "cypress";
import { addMatchImageSnapshotPlugin } from "cypress-image-snapshot/plugin";
export default defineConfig({
e2e: {
setupNodeEvents(on) {
// Register the Node-side handler that writes and diffs PNGs
addMatchImageSnapshotPlugin(on);
},
},
});
With the command registered, a test captures a named snapshot. The name is the identity of the baseline file, so it must be unique and stable.
// cypress/e2e/visual/cart.cy.ts
describe("cart page", () => {
it("matches the empty cart snapshot", () => {
cy.visit("/cart");
// Capture the visible viewport and diff it against the baseline named "empty-cart"
cy.matchImageSnapshot("empty-cart");
});
});
On the first run, the command writes cypress/snapshots/visual/cart.cy.ts/empty-cart.png and passes. On the second run, it writes a temporary screenshot, diffs it against the baseline, and fails with a diff image if the mismatch exceeds the threshold. The diff artifacts land next to the baseline: a __diff_output__ folder holds the highlighted difference and the received image, which is how a reviewer sees what moved.
b. Scoping the capture and tolerating noise
A full-viewport snapshot is brittle on a long page: a single lazy-loaded image at the bottom changes the diff. The clip option scopes the capture to a rectangle, and capturing a component rather than the whole page is the standard way to keep a visual test focused.
it("matches the product card only", () => {
cy.visit("/products");
cy.get("[data-testid=product-card]").first().then(($card) => {
// Derive the clip rectangle from the element's bounding box
const { x, y, width, height } = $card[0].getBoundingClientRect();
cy.matchImageSnapshot("product-card", {
clip: { x, y, width, height },
});
});
});
Some pixels are legitimately unstable: text anti-aliasing differs between machines, and animated spinners are never the same twice. The customDiffConfig.threshold sets per-pixel color tolerance (a value of 0.1 means a channel may shift by roughly 10% and still count as equal), while failureThreshold sets how many pixels may differ overall. Both matter: the per-pixel tolerance absorbs rendering noise, and the percentage threshold absorbs a handful of scattered pixels while still catching a real layout shift.
// Stable capture: generous per-pixel tolerance, strict overall budget
cy.matchImageSnapshot("dashboard", {
customDiffConfig: { threshold: 0.2 }, // tolerate font-rendering noise
failureThreshold: 0.005, // but only 0.5% of pixels overall
failureThresholdType: "percent",
});
A dynamic region โ a timestamp, a randomized avatar, an ad slot โ should be masked or removed before capture rather than tolerated in the threshold. The clean approach is to freeze the data with cy.intercept so the page renders deterministically, and the screenshot then needs no mask at all.
it("snapshots the order summary with frozen data", () => {
// Stub the API so the timestamp and totals are always identical
cy.intercept("GET", "/api/orders/42", { fixture: "order-42.json" });
cy.visit("/orders/42");
cy.matchImageSnapshot("order-summary");
});
c. Percy: cloud snapshots across browsers and widths
Percy inverts the storage model. There is no committed baseline in the repo; each cy.percySnapshot() uploads the DOM and asset snapshot to Percy’s cloud, and Percy re-renders it in its own browsers at its own widths, then diffs against the approved baseline stored in the Percy project. The comparison happens server-side, and a human approves or rejects the diff in the Percy web UI before it can affect the build.
The setup is the @percy/cypress package plus the percy exec wrapper around the test run.
// cypress/support/e2e.ts
import "@percy/cypress"; // registers cy.percySnapshot()
The snapshot call takes a name and optional width list. The widths are where Percy earns its keep: one call renders the page at desktop and mobile widths in the same snapshot, and each width gets its own diff.
// cypress/e2e/visual/home.cy.ts
describe("home page", () => {
it("captures the hero across viewports", () => {
cy.visit("/");
cy.get("[data-testid=hero]").should("be.visible");
// Percy renders this at each width and diffs per width
cy.percySnapshot("home-hero", { widths: [375, 768, 1280] });
});
});
The run is wrapped so Percy can tag the build and associate snapshots with a branch and commit.
# The wrapper injects PERCY_* env vars and flushes snapshots at the end
PERCY_TOKEN=$PERCY_TOKEN npx percy exec -- cypress run
Snapshots captured through a stub are the same discipline as with image snapshots โ freeze the data so the diff reflects style, not content.
cy.intercept("GET", "/api/recommendations", { fixture: "recs.json" });
cy.visit("/");
cy.percySnapshot("recommendations", { widths: [375, 1280] });
The key difference in workflow: a cypress-image-snapshot failure is resolved in the repo by regenerating and committing a PNG, while a Percy failure is resolved in the Percy UI by approving the new baseline, after which the build goes green. Percy’s review model is what makes it viable for a team where not everyone can run the full browser matrix locally.
Complete Example Session
// ============================================
// PART 1: THE IMAGE SNAPSHOT COMMAND SETUP
// ============================================
// cypress/support/commands.ts
import { addMatchImageSnapshotCommand } from "cypress-image-snapshot/command";
addMatchImageSnapshotCommand({
failureThreshold: 0.01,
failureThresholdType: "percent",
customDiffConfig: { threshold: 0.1 },
});
// ============================================
// PART 2: THE PLUGIN REGISTRATION
// ============================================
// cypress.config.ts
import { defineConfig } from "cypress";
import { addMatchImageSnapshotPlugin } from "cypress-image-snapshot/plugin";
export default defineConfig({
e2e: {
setupNodeEvents(on) {
addMatchImageSnapshotPlugin(on);
},
},
});
// ============================================
// PART 3: A FULL-PAGE SNAPSHOT TEST
// ============================================
// cypress/e2e/visual/cart.cy.ts
describe("cart page", () => {
it("matches the empty cart snapshot", () => {
cy.visit("/cart");
cy.matchImageSnapshot("empty-cart");
});
});
// ============================================
// PART 4: A SCOPED COMPONENT SNAPSHOT
// ============================================
it("matches the product card only", () => {
cy.visit("/products");
cy.get("[data-testid=product-card]").first().then(($card) => {
const { x, y, width, height } = $card[0].getBoundingClientRect();
cy.matchImageSnapshot("product-card", {
clip: { x, y, width, height },
});
});
});
// ============================================
// PART 5: NOISE TOLERANCE CONFIG
// ============================================
cy.matchImageSnapshot("dashboard", {
customDiffConfig: { threshold: 0.2 },
failureThreshold: 0.005,
failureThresholdType: "percent",
});
// ============================================
// PART 6: FREEZING DYNAMIC DATA
// ============================================
it("snapshots the order summary with frozen data", () => {
cy.intercept("GET", "/api/orders/42", { fixture: "order-42.json" });
cy.visit("/orders/42");
cy.matchImageSnapshot("order-summary");
});
// ============================================
// PART 7: THE PERCY SUPPORT IMPORT
// ============================================
// cypress/support/e2e.ts
import "@percy/cypress";
// ============================================
// PART 8: A PERCY SNAPSHOT ACROSS WIDTHS
// ============================================
describe("home page", () => {
it("captures the hero across viewports", () => {
cy.visit("/");
cy.get("[data-testid=hero]").should("be.visible");
cy.percySnapshot("home-hero", { widths: [375, 768, 1280] });
});
});
// ============================================
// PART 9: THE PERCY RUN COMMAND
// ============================================
// Run through the percy wrapper so snapshots attach to a build
// npx percy exec -- cypress run
// ============================================
// PART 10: THE DETERMINISTIC PERCY SNAPSHOT
// ============================================
cy.intercept("GET", "/api/recommendations", { fixture: "recs.json" });
cy.visit("/");
cy.percySnapshot("recommendations", { widths: [375, 1280] });
The ten parts covered the command registration, the Node-side plugin, a full-page snapshot, a clipped component snapshot, the tolerance configuration, data freezing, the Percy import, a multi-width Percy snapshot, the wrapper command, and a deterministic Percy capture.
Quick Reference
cypress-image-snapshot Options
| Option | Meaning |
|---|---|
failureThreshold | Allowed differing pixels (number or percent) |
failureThresholdType | "pixel" or "percent" |
customDiffConfig.threshold | Per-pixel color tolerance (0โ1) |
clip | Rectangle { x, y, width, height } to capture |
snapshotIdentifier | Override the baseline file name |
Percy Snapshot Options
| Option | Meaning |
|---|---|
name | Snapshot name shown in the Percy UI |
widths | Array of viewport widths to render |
minHeight | Minimum snapshot height |
percyCSS | Extra CSS injected only for the snapshot |
The Two Approaches
| Aspect | cypress-image-snapshot | Percy |
|---|---|---|
| Baseline location | Repo (cypress/snapshots) | Percy cloud project |
| Comparison | Local Node process | Percy servers |
| Browsers | Only the one Cypress ran | Percy’s browser matrix |
| Approval | Commit the new PNG | Approve in Percy UI |
| Cost | Free, open source | Paid service |
Run Commands
| Task | Command |
|---|---|
| Update image baselines | cypress run --env updateSnapshots=true |
| Run Percy suite | npx percy exec -- cypress run |
| Local image test | npx cypress open |
Best Practices
โ Do This:
// Pin the CI container so pixels are stable
image: cypress/browsers:node20.15.0-chrome127 // โ
// Freeze API data before capturing
cy.intercept("GET", "/api/cart", { fixture: "cart.json" }); // โ
// Scope the snapshot to a component
cy.matchImageSnapshot("card", { clip: box }); // โ
// Set a per-pixel tolerance for font noise
customDiffConfig: { threshold: 0.15 } // โ
// Snapshot at multiple widths with Percy
cy.percySnapshot("hero", { widths: [375, 1280] }); // โ
// Commit baselines together with the UI change
git add cypress/snapshots/ && git commit -m "update baselines" // โ
โ Don’t Do This:
// Generate baselines on macOS, run CI on Linux
cy.matchImageSnapshot("page"); // โ fonts render differently
// Snapshot a page with a live timestamp
cy.visit("/dashboard"); // โ diff every run
// Use a zero threshold on text-heavy pages
failureThreshold: 0 // โ anti-aliasing flakes
// Approve a Percy diff without inspecting it
// (defeats the review model) // โ
// Snapshot the whole long page by default
cy.matchImageSnapshot("full-page"); // โ lazy content shifts
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Every run fails on CI | Baselines made on a different OS | Regenerate inside the CI image |
| Tiny diffs everywhere | Anti-aliasing differences | Raise customDiffConfig.threshold |
| Diff on an animated element | Spinner or transition captured mid-state | Disable animations before capture |
| Baseline name collision | Two tests share a snapshot name | Use unique names per test |
| Percy snapshots never appear | Run not wrapped in percy exec | Use npx percy exec -- cypress run |
| Flaky lazy-loaded images | Below-fold images load late | Stub images or scope the clip |
| Stale baselines approved blind | No review discipline | Require diff inspection in PRs |
Real-World Examples
1. Full-page cart snapshot
cy.visit("/cart");
cy.matchImageSnapshot("empty-cart");
2. Component clip
const box = el[0].getBoundingClientRect();
cy.matchImageSnapshot("card", { clip: box });
3. Percent threshold
cy.matchImageSnapshot("dash", { failureThreshold: 0.01, failureThresholdType: "percent" });
4. Pixel tolerance
cy.matchImageSnapshot("dash", { customDiffConfig: { threshold: 0.2 } });
5. Update baselines
// cypress run --env updateSnapshots=true
6. Percy multi-width
cy.percySnapshot("home", { widths: [375, 768, 1280] });
7. Percy run wrapper
npx percy exec -- cypress run
8. Freeze data first
cy.intercept("GET", "/api/orders", { fixture: "orders.json" });
9. Percy-only CSS
cy.percySnapshot("home", { percyCSS: ".ad { display: none; }" });
10. Disable animations
cy.get("body").invoke("css", "animation", "none");
Visual
The Image Snapshot Pipeline
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ cypress-image-snapshot PIPELINE โ
โ โ
โ test runs โโโบ cy.matchImageSnapshot("cart") โ
โ โ โ
โ โผ โ
โ baseline exists? โโnoโโโบ write baseline PNG, PASS โ
โ โ โ
โ yes โ
โ โผ โ
โ capture new PNG โโโบ diff against baseline โ
โ โ โ
โ โโโโโโโโโโโโโดโโโโโโโโโโโโ โ
โ โผ โผ โ
โ within threshold over threshold โ
โ PASS FAIL + diff_output โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Percy Pipeline
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ PERCY PIPELINE โ
โ โ
โ cypress run โ
โ โ โ
โ โผ โ
โ cy.percySnapshot("home", { widths: [...] }) โ
โ โ โ
โ โผ โ
โ upload DOM + assets to Percy cloud โ
โ โ โ
โ โผ โ
โ Percy renders at each width in its browsers โ
โ โ โ
โ โผ โ
โ diff vs approved baseline โโโบ Percy UI review โ
โ โ โ
โ โโโ approved โโโบ build passes โ
โ โโโ rejected โโโบ build fails โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Baseline Storage
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ WHERE THE BASELINE LIVES โ
โ โ
โ cypress-image-snapshot Percy โ
โ โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ โ
โ โ git repo โ โ Percy cloud โ โ
โ โ cypress/ โ โ project baseline โ โ
โ โ snapshots/ โ โ approved in UI โ โ
โ โ *.png โ โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ โ
โ commit to review approve to review โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Capturing Scope
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CAPTURE SCOPE โ
โ โ
โ viewport โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ header โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โ โ product card โ โ โ
โ โ โ (clip target) โ โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โ footer โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ full viewport = brittle clip = focused and stable โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Image command | cy.matchImageSnapshot() |
| Image plugin | addMatchImageSnapshotPlugin(on) |
| Baseline location | cypress/snapshots/ in the repo |
| Percy command | cy.percySnapshot() |
| Percy wrapper | npx percy exec -- cypress run |
| Noise control | customDiffConfig.threshold |
| Diff budget | failureThreshold + type |
| Scoping option | clip rectangle |
| Percy widths | widths: [375, 768, 1280] |
| Determinism tool | cy.intercept fixtures |
Key takeaways:
- Visual testing is capture plus compare. Cypress captures the screenshot;
cypress-image-snapshotor Percy performs the diff against a stored baseline. Neither tool replaces the other’s role, and Cypress alone does not diff pixels. - Baselines are environment-bound. Font rendering, anti-aliasing, and device pixel ratio change pixels without changing the page. Baselines must be generated in the same container CI uses, or every run fails for the wrong reason.
cypress-image-snapshotkeeps baselines in the repo. It is free, offline, and reviewed through pull requests, but it only covers the single browser Cypress ran in and the developer must regenerate PNGs when a UI change is intentional.- Percy renders in the cloud across browsers and widths. It is a paid service whose value is the browser matrix and the visual review UI, and it requires the
percy execwrapper so snapshots attach to a build. - Determinism is the discipline. Freeze API data with
cy.intercept, scope the capture withclip, disable animations, and tune per-pixel tolerance before raising the overall pixel budget.
Remember: Visual testing exists because functional assertions cannot see pixels. Capture the smallest stable region, freeze the data that feeds it, tune the tolerances to absorb rendering noise rather than real shifts, and choose storage deliberately: committed PNGs via cypress-image-snapshot when the team can pin the environment, or Percy when the browser-and-width matrix and a review UI are worth the service cost.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!