Visual Regression Testing with Storybook: Chromatic and Percy Integration
Visual regression tests catch the changes that functional tests miss. A button with the wrong font weight still passes a click test. A card component with a broken layout still passes an existence check. Visual regression testing captures a pixel-level snapshot of your component and fails when it changes unexpectedly.
Storybook is the natural place to run visual regression. Every story is already a component rendered in a specific state — it's a ready-made set of visual test cases. You don't need to write additional setup code. The stories you're already maintaining become your visual baseline.
This post covers two approaches: Chromatic (the purpose-built Storybook solution) and Percy (a popular alternative), plus techniques for handling dynamic content that would otherwise cause false positives.
How Visual Regression Testing Works
The workflow is always the same regardless of tool:
- Render the component in a specific state
- Capture a screenshot (the baseline)
- On subsequent runs, render the same component, capture a new screenshot
- Diff the two images pixel by pixel
- Flag anything that changed beyond a configurable threshold
The challenge is separating intentional changes from regressions. When you update a button's border radius, that's an intentional change — you want to approve it and update the baseline. When a dependency update shifts some spacing by two pixels, that's a regression you want to catch and revert.
Option 1: Chromatic
Chromatic is built by the Storybook team. It handles snapshot capture, cloud storage, diffing, and a review UI. Setup is minimal.
Installation and First Run
npm install --save-dev chromaticRun your first build to establish the baseline:
npx chromatic --project-token=<your-token>Chromatic uploads your Storybook build to their CDN, renders every story in their cloud infrastructure across multiple browsers, and stores the snapshots as the baseline. The first run always passes — it's just establishing what "correct" looks like.
CI Integration
Add to your GitHub Actions workflow:
name: Visual Regression
on: [push, pull_request]
jobs:
chromatic:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # Required for Chromatic to detect changed stories
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- name: Run Chromatic
uses: chromaui/action@latest
with:
projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
exitZeroOnChanges: true # Don't fail CI, require human review
autoAcceptChanges: main # Auto-accept on main branch mergesexitZeroOnChanges: true is important for team workflows — it means CI doesn't block on visual changes, but Chromatic will prevent PRs from merging in GitHub until someone reviews and accepts the changes in the Chromatic UI.
Reviewing Changes
When Chromatic detects a visual difference, it shows a side-by-side comparison in the review UI:
- Green overlay: pixels that haven't changed
- Red overlay: pixels that changed
- Toggle between baseline and new snapshot
You accept (intentional change, update baseline) or deny (regression, don't merge). Accepted changes become the new baseline for future comparisons.
Storybook Modes for Multi-Theme Testing
If your application supports multiple themes or viewports, Chromatic's Modes feature captures a snapshot for each combination:
// .storybook/modes.ts
export const allModes = {
light: { theme: 'light' },
dark: { theme: 'dark' },
mobile: { viewport: 'mobile' },
desktop: { viewport: 'desktop' },
};// Button.stories.ts
import { allModes } from '../.storybook/modes';
export const Primary: Story = {
parameters: {
chromatic: {
modes: {
light: allModes.light,
dark: allModes.dark,
},
},
},
};Each mode generates a separate snapshot. A single story can produce four snapshots: light + mobile, light + desktop, dark + mobile, dark + desktop.
Option 2: Percy
Percy (now BrowserStack Percy) is a visual testing platform that's not tied to Storybook. It works with Storybook, but also with Cypress, Playwright, Selenium, and custom screenshot scripts.
Installation
npm install --save-dev @percy/storybook @percy/cliRunning Percy Against Storybook
Percy has a dedicated Storybook integration that crawls your stories and captures snapshots:
percy storybook http://localhost:6006In CI:
- name: Build Storybook
run: npm run build-storybook
- name: Run Percy
run: npx percy storybook ./storybook-static
env:
PERCY_TOKEN: ${{ secrets.PERCY_TOKEN }}Percy renders your Storybook static build (no server required), captures snapshots, and uploads them to their cloud for diffing.
Percy vs Chromatic: Key Differences
| Aspect | Chromatic | Percy |
|---|---|---|
| Storybook integration | Native, purpose-built | Plugin-based |
| Other framework support | Storybook only | Cypress, Playwright, Selenium |
| Pricing model | Per snapshot | Per screenshot |
| Review UI | Chromatic dashboard | Percy dashboard |
| CI blocking | GitHub PR check | GitHub PR check |
| Free tier | 5,000 snapshots/month | 5,000 screenshots/month |
If you're already using Percy for Cypress E2E visual testing, extending it to Storybook makes sense. If Storybook is your primary testing tool, Chromatic's native integration is lower friction.
Handling Dynamic Content
Dynamic content causes false positives — your test fails not because anything broke, but because a timestamp changed or a random avatar loaded differently. You need to stabilize these before visual regression testing is useful.
Hiding Dynamic Elements
Chromatic and Percy both support hiding elements from screenshots:
export const WithDynamicContent: Story = {
parameters: {
chromatic: {
diffThreshold: 0.2, // Allow minor pixel differences
},
},
decorators: [
(Story) => (
<div>
<Story />
{/* Hide timestamps from visual snapshots */}
<style>{`[data-testid="timestamp"] { visibility: hidden; }`}</style>
</div>
),
],
};For Percy, use data-percy-hide attribute:
<span data-percy-hide>{new Date().toISOString()}</span>Freezing Dates and Random Values
Use beforeEach in your story's loaders or decorators to stabilize time-dependent rendering:
// .storybook/preview.ts
import MockDate from 'mockdate';
export const decorators = [
(Story) => {
MockDate.set('2025-01-15T10:00:00Z');
return <Story />;
},
];For random IDs or UUIDs generated during render:
import { vi } from 'vitest';
// In your story file
vi.mock('uuid', () => ({
v4: () => 'fixed-uuid-for-testing',
}));Handling Animations
CSS animations cause flaky visual tests because the screenshot might capture mid-animation. Disable them globally:
// .storybook/preview.ts
export const parameters = {
chromatic: {
// Wait for animations to complete before capturing
delay: 300,
// Or disable animations via CSS
},
};Alternatively, add a global CSS rule that disables animations during visual testing:
/* injected during Chromatic/Percy runs */
*, *::before, *::after {
animation-duration: 0ms !important;
transition-duration: 0ms !important;
}You can detect the Percy/Chromatic environment and apply this conditionally:
// .storybook/preview.ts
if (window.location.href.includes('iframe.html')) {
const style = document.createElement('style');
style.textContent = '*, *::before, *::after { animation-duration: 0ms !important; }';
document.head.appendChild(style);
}Baseline Management
Managing baselines is where visual regression testing gets operationally complex. A few principles:
Accept changes on the main branch automatically. When a PR is merged and the visual change was intentional, auto-accept it as the new baseline. Both Chromatic (autoAcceptChanges: main) and Percy have this option.
Never update baselines in CI without a human review. The whole point of visual regression is that a human verifies the change is intentional. Automating baseline acceptance on every CI run defeats the purpose.
Keep story states minimal and deterministic. The more complex and stateful a story is, the more likely it is to produce noise. Prefer stories with static data and predictable rendering.
Use story-level opt-out for known flaky stories. Some components are genuinely hard to snapshot consistently (infinite scrollers, canvas-based renderers, streaming content). Opt them out rather than fighting the noise:
export const InfiniteScroll: Story = {
parameters: {
chromatic: { disableSnapshot: true },
},
};Chromatic Turbosnap: Only Test Changed Components
Chromatic's TurboSnap feature analyzes your git diff and only re-captures snapshots for stories whose underlying component files changed. For large component libraries this can reduce snapshot counts by 80–90%.
- name: Run Chromatic with TurboSnap
uses: chromaui/action@latest
with:
projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
onlyChanged: true # Enable TurboSnapTurboSnap requires fetch-depth: 0 in your checkout step so Chromatic can analyze the full git history.
What Visual Regression Testing Doesn't Cover
Visual regression testing at the component level catches component-level regressions: a button that changed color, a card that broke its layout, an icon that disappeared. It does not catch:
- Page-level layout issues caused by component composition
- Interaction-dependent visual states (what does the dropdown look like after clicking it three times?)
- Cross-browser rendering differences unless you explicitly test multiple browsers
- Visual issues in flows that span multiple pages
For full-page and cross-journey visual testing, you need end-to-end tests. HelpMeTest includes AI-powered visual diff checking in its E2E test runner — it captures screenshots at key points during a user journey and alerts you when the visual output changes unexpectedly, complementing the component-level coverage you get from Chromatic or Percy.
Summary
Visual regression testing with Storybook is practical and low-maintenance once configured. Chromatic is the easiest path if Storybook is your primary component testing environment. Percy makes sense if you're already using it elsewhere. The key operational concerns — dynamic content, baseline management, and animation handling — are all solvable with a few lines of configuration. The payoff is catching the class of regressions that functional tests systematically miss.