# Storybook Visual Testing Suite with Chromatic, Playwright, and Custom Diff Heuristics
# For Interactive States (Hover, Focus, Click, etc.)
# This guide composes a complete visual regression testing suite for Storybook.
# It combines:
# - **Chromatic**: Cloud-based visual reviews & baselines for static + interactive stories.
# - **Playwright** (via @storybook/test-runner): Drives interactions (hover, focus, etc.) and captures snapshots.
# - **Custom Diff Heuristics**: Extends Playwright's pixelmatch with perceptual diffing (resemble.js),
# anti-aliasing tolerance, and dynamic thresholds for interactive states (e.g., ignore subtle shadows/transitions).
# Prerequisites:
# - Node.js 18+
# - Existing Storybook project (create with `npx storybook@latest init` if needed)
# - Chromatic project (sign up at chromatic.com, get PROJECT_TOKEN)
1. Installation & Dependencies
npm install --save-dev \
@storybook/test-runner \
@playwright/test \
playwright \
resemblejs \
chromatic \
@chromatic-com/storybook \
pixelmatch \
pngjs
# Install Playwright browsers
npx playwright install
package.json scripts (add these):
{
"scripts": {
"test-storybook": "test-storybook",
"test-storybook:ci": "test-storybook --ci --url http://localhost:6006",
"chromatic": "chromatic --storybook-build-dir=storybook-static",
"visual-test": "npm run build-storybook && npm run test-storybook",
"visual-test:ci": "npm run build-storybook && npm run test-storybook:ci && npm run chromatic"
}
}
2. Storybook Configuration
.storybook/main.ts (enable test runner & Chromatic addon):
import type { StorybookConfig } from '@storybook/react-vite'; // Adjust for your framework
const config: StorybookConfig = {
// ... your existing config
addons: [
// ... existing addons
'@chromatic-com/storybook',
'@storybook/addon-interactions', // For interaction stories
],
framework: {
name: '@storybook/test-runner',
options: {},
},
};
export default config;
Build Storybook for static hosting (.storybook/preview.ts):
import type { Preview } from '@storybook/react';
const preview: Preview = {
parameters: {
chromatic: { disableSnapshot: false },
// Enable interactions globally
actions: { argTypesRegex: '^on[A-Z].*' },
controls: { matchers: { color: /(background|color)$/i, date: /Date$/ } },
},
};
export default preview;
3. Playwright Configuration
playwright.config.ts (customize for Storybook):
import { defineConfig, devices } from '@playwright/test';
import { testRunnerConfig } from '@storybook/test-runner';
export default defineConfig({
...testRunnerConfig(), // Storybook defaults (chromium, viewport 1280x720, etc.)
testDir: './storybook-tests', // Folder for test files
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: [['html'], ['json', { outputFile: 'playwright-report.json' }]],
use: {
...devices['Desktop Chrome'],
actionTimeout: 5000,
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
],
});
4. Example Story with Interactive States
stories/Button.stories.ts (define static + interactive variants):
import type { Meta, StoryObj } from '@storybook/react';
import { Button } from './Button';
const meta: Meta<typeof Button> = {
title: 'Components/Button',
component: Button,
parameters: {
// Chromatic will snapshot these args automatically
chromatic: { viewports: [320, 1200] },
},
argTypes: {
variant: { control: 'radio', options: ['primary', 'secondary'] },
},
};
export default meta;
type Story = StoryObj<typeof meta>;
export const Default: Story = {
args: { children: 'Click me', variant: 'primary' },
};
export const Hover: Story = {
parameters: {
// Mark for interaction testing
pseudo: { hover: true },
},
args: { ...Default.args },
};
export const Focused: Story = {
parameters: {
pseudo: { focusVisible: true },
},
args: { ...Default.args },
};
export const Loading: Story = {
play: async ({ canvasElement }) => {
// Storybook interaction (Chromatic/Playwright can play these)
await userEvent.click(canvasElement.querySelector('button')!);
},
args: { children: 'Click to Load', isLoading: true },
};
5. Playwright Test Suite for Interactive States
Create storybook-tests/button.spec.ts (drive interactions, custom snapshots):
import { test, expect } from '@playwright/test';
import { checkHtml, checkAccessibility } from '@storybook/test';
// Custom diff comparator with heuristics for interactive states
async function customScreenshotMatch(
page: any,
name: string,
options: any = {}
) {
const screenshot = await page.screenshot({ fullPage: true });
// Load resemble.js for perceptual diffing
const resemble = require('resemblejs').default;
// Custom heuristics:
// - Perceptual diff (ignores anti-aliasing, minor color shifts)
// - Threshold: 5% for interactive states (higher tolerance for shadows/transitions)
// - Ignore regions: e.g., timestamps, animations
const diff = await resemble(
options.baselinePath || `screenshots/${name}-baseline.png`, // Assume baselines committed
screenshot
).compareTo(options.baselinePath || `screenshots/${name}-baseline.png`);
expect(diff.misMatchPercentage).toBeLessThan(
options.threshold || 5 // Custom threshold for interactive states
);
if (diff.misMatchPercentage > 0) {
require('fs').writeFileSync(`screenshots/${name}-diff.png`, diff.getImageDataUrl());
}
}
test.describe('Button Interactive States', () => {
test('Default static snapshot @chromatic-ignore', async ({ page }) => {
await page.goto('/story/components-button--default');
await checkHtml(page);
await expect(page).toHaveScreenshot('button-default.png');
});
test('Hover state with custom diff', async ({ page }) => {
await page.goto('/story/components-button--hover');
await page.hover('button'); // Ensure hover
await page.waitForTimeout(200); // Stabilize transition
await customScreenshotMatch(page, 'button-hover', { threshold: 3 });
});
test('Focus state', async ({ page }) => {
await page.goto('/story/components-button--focused');
await page.focus('button');
await customScreenshotMatch(page, 'button-focus', { threshold: 4 });
});
test('Click & Loading interaction', async ({ page }) => {
await page.goto('/story/components-button--loading');
await page.click('button');
await page.waitForSelector('[data-loading="true"]');
await expect(page).toHaveScreenshot('button-loading.png', {
// Playwright built-in options + custom mask for dynamic elements
mask: [page.locator('[data-timestamp]')],
maxDiffPixels: 100, // Ignore small pixel changes
});
await checkAccessibility(page);
});
});
6. Chromatic Configuration
chromatic.config.js (integrate Playwright tests, custom build):
module.exports = {
projectToken: process.env.CHROMATIC_PROJECT_TOKEN!, // Set in .env
buildScriptName: 'build-storybook',
onlyStoryFiles: ['**/*.stories.@(js|jsx|ts|tsx)'],
storybookConfigDir: '.storybook',
// Run Playwright tests during build for interaction snapshots
runStorybook: {
postbuildCommand: 'npx playwright test --project=chromium',
},
// Custom diff tolerances (Chromatic supports via UI, but override locally)
diffs: {
threshold: 0.1, // 0.1% pixel diff tolerance
},
};
.chromatic/workflows/push.yml (GitHub Action example):
name: Chromatic
on: [push, pull_request]
jobs:
chromatic:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Install dependencies
run: npm ci
- name: Build Storybook
run: npm run build-storybook
- name: Run Playwright tests
run: npm run test-storybook:ci
env:
PLAYWRIGHT_TEST_BASE_URL: http://localhost:6006
- uses: chromaui/action@v1
with:
projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
token: ${{ secrets.GITHUB_TOKEN }}
7. Running the Suite
# Local development
npm run storybook # http://localhost:6006
npm run visual-test # Build + test interactions
# CI (with Chromatic review)
npm run visual-test:ci
# Update baselines (local only)
npx playwright test --update-snapshots
Key Features & Heuristics Explained
- Static Stories: Chromatic snapshots automatically.
- Interactive States: Playwright drives hover/focus/click;
pseudo params for CSS-only.
- Custom Diffs:
| Heuristic | Purpose | Implementation |
|---|
| Perceptual (resemble.js) | Ignore color/anti-aliasing noise | misMatchPercentage < 5% |
| Dynamic Thresholds | Tolerant for hovers/shadows | 3-5% vs. 0.1% strict |
| Masks | Ignore timestamps/animations | Playwright mask |
| Max Diff Pixels | Small changes OK | maxDiffPixels: 100 |
- Approvals: Chromatic UI for reviewing diffs; auto-approve minor changes via thresholds.
- Scalability: Parallel workers, CI integration.
This suite catches regressions in interactive UIs while tolerating non-critical diffs. Extend customScreenshotMatch for app-specific rules (e.g., ignore user avatars). Baselines are committed to git; Chromatic handles cloud reviews.