We are going to set up a Storybook visual testing suite that uses:
- Chromatic for automated visual regression testing (snapshots) and to run Storybook in the cloud.
- Playwright for testing interactive states (since Chromatic's snapshot testing is static and doesn't cover interactions).
- Custom diff heuristics to compare images, especially for interactive states that might have dynamic content (like hover, focus, etc.).
Steps:
-
Setup Storybook with Chromatic:
- We assume the project already has Storybook set up. If not, we can set it up with
npx storybook@latest init.
- Install Chromatic:
npx chromatic@latest --project-token <your-project-token>
-
Integrate Playwright with Storybook:
- We can use Playwright to interact with the Storybook UI and take screenshots at different states.
- We can write Playwright tests that navigate to the Storybook instance (either locally or using Chromatic's published story) and interact with components.
-
Custom Diff Heuristics:
- We can use a tool like
pixelmatch or resemble.js to compare images with custom thresholds or ignore certain regions (like dynamic text, timestamps, etc.).
- We can create a helper function that takes two images (baseline and current) and returns a diff score, and then we can assert based on a custom threshold.
-
Workflow:
-
We will use Chromatic to capture the initial baseline for each story (static state). Chromatic will handle the baseline for static snapshots.
-
For interactive states, we will write Playwright tests that:
a. Navigate to the Storybook page (either the local dev server or the Chromatic published URL for that build).
b. Interact with the component (hover, click, etc.)
c. Take a screenshot.
d. Compare with a baseline screenshot (which we have to capture manually or via an initial run) using our custom diff.
-
Alternatively, we can use Chromatic's ---storybook-build-dir to run Playwright against the built Storybook from Chromatic, so we are testing the exact same build.
-
Implementation:
a. Install Dependencies:
```bash
# For Chromatic
npm install -D chromatic
# For Playwright
npm install -D @playwright/test
# For image diffing (example with pixelmatch)
npm install -D pixelmatch
```
b. Configure Playwright:
Create a `playwright.config.ts` (or .js) file. We'll set up a project that points to the Storybook build directory (if using Chromatic) or the local dev server.
Example config (for Chromatic build):
```typescript
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: 'html',
use: {
baseURL: `file://${process.env.STORYBOOK_BUILD_DIR || './storybook-static'}`,
trace: 'on-first-retry',
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
],
});
```
c. Write a Playwright test for interactive state:
Suppose we have a button that changes color on hover. We want to test that.
We can write a test in `tests/button.spec.ts`:
```typescript
import { test, expect } from '@playwright/test';
import { pixelmatch } from 'pixelmatch';
import { readFileSync, writeFileSync } from 'fs';
import { join } from 'path';
test('button hover state', async ({ page }) => {
// Navigate to the button story in the built Storybook
await page.goto('/iframe.html?args=&id=button--hover'); // adjust the id and args as needed
// The button might be inside an iframe. We may need to handle iframes.
// Alternatively, we can use the direct story URL without iframe if we have set `previewUrl` in Chromatic.
// Wait for the component to be visible
const button = page.locator('#button-id'); // use a more specific selector, maybe by story id
// Take a screenshot of the initial state (optional, if we want to compare with baseline)
// But note: we are comparing with a baseline that we already have for hover state.
// Hover over the button
await button.hover();
// Take a screenshot of the hover state
const hoverScreenshot = await page.screenshot();
// Read the baseline hover screenshot (we have to store it somewhere, e.g., in a `baseline` folder)
const baselinePath = join(__dirname, 'baseline', 'button-hover.png');
const baseline = readFileSync(baselinePath);
// Compare the two images
const { width, height } = await page.evaluate(() => ({
width: document.body.scrollWidth,
height: document.body.scrollHeight,
}));
// Create a canvas to do the diff (pixelmatch works on raw pixel data)
const img1 = await page.evaluate((data) => {
const img = new Image();
img.src = 'data:image/png;base64,' + data.toString('base64');
return img;
}, hoverScreenshot);
// But note: pixelmatch requires two ImageData objects. We can use canvas to get ImageData.
// Alternatively, we can use `resemble.js` which can compare two images and give a diff image and mismatch percentage.
// Let's use `pixelmatch` with a threshold and also generate a diff image for debugging.
const canvas = await page.evaluate((width, height) => {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
return canvas;
}, width, height);
const ctx = await page.evaluate((canvas) => canvas.getContext('2d'), canvas);
await page.evaluate((ctx, imgData) => {
ctx.putImageData(imgData, 0, 0);
}, ctx, hoverScreenshot);
// Actually, we can do the comparison in Node.js without using the page's canvas.
// We can use `sharp` to get the raw pixel data? But pixelmatch expects ImageData (with width, height, data and各方面的信息).
// Alternatively, let's use `resemble.js` which is easier for basic diffing.
// But note: we are already in a Node environment (the test runs in Node). We can read the two images as buffers and then use `resemble`:
const resemble = require('resemblejs');
resemble(baseline).compareTo(hoverScreenshot).onComplete((data) => {
// data.mismatch is the percentage of pixels that are different
expect(data.mismatch).toBeLessThan(1); // 1% threshold, for example
});
// However, note that `resemble.js` doesn't return a promise by default. We can promisify it.
// Alternatively, we can use `pixelmatch` with a threshold and also generate a diff image.
// Let's do:
const baselineImg = readFileSync(baselinePath);
const currentImg = hoverScreenshot;
// We need to decode both images to get their raw pixel data and dimensions. We can use `pngjs` or `jimp`.
// Actually, `pixelmatch` works with raw RGBA buffers. We can use `pngjs` to read the PNGs.
// But note: the screenshots from Playwright are PNGs.
// We can do:
const PNG = require('pngjs').PNG;
const fs = require('fs');
function getImageData(buffer) {
const png = PNG.sync.read(buffer);
return {
width: png.width,
height: png.height,
data: png.data,
};
}
const img1 = getImageData(baseline);
const img2 = getImageData(currentImg);
const { width: w, height: h, data: data1 } = img1;
const { data: data2 } = img2;
// Make sure dimensions match
expect(w).toBe(img2.width);
expect(h).toBe(img2.height);
const diff = new PNG({ width: w, height: h });
const numDiffPixels = pixelmatch(data1, data2, diff.data, w, h, {
threshold: 0.1,
});
const diffPercent = (numDiffPixels / (w * h)) * 100;
// Optionally, write the diff image for debugging
writeFileSync(join(__dirname, 'diff', 'button-hover-diff.png'), PNG.sync.write(diff));
expect(diffPercent).toBeLessThan(1); // 1% threshold
// But note: the above code is synchronous and might be slow for large images. We can use the async version of pixelmatch?
// Actually, pixelmatch is synchronous. For our purpose (component screenshots) it's acceptable.
});
```
d. Running the tests:
We can run the Playwright tests against the Storybook build. We can do:
```bash
# Build Storybook (if using Chromatic, they build it for you, but you can also build locally)
npx storybook build
# Then run Playwright tests pointing to the built Storybook (storybook-static)
npx playwright test --baseURL=file://<absolute-path-to>/storybook-static
```
Alternatively, if we want to run against Chromatic's published story, we can set the baseURL to the Chromatic story URL.
e. Integrating with Chromatic:
Chromatic runs Storybook and takes static snapshots for every story. We want to also run our Playwright tests for interactive states on the same build.
We can use Chromatic's `--storybook-build-dir` to specify the build directory, and then run Playwright against that directory.
We can set up a script:
```json
{
"scripts": {
"chromatic": "chromatic --project-token=<token> --storybook-build-dir=storybook-static",
"test:visual": "npm run build:storybook && playwright test --baseURL=file://$(pwd)/storybook-static",
"build:storybook": "storybook build"
}
}
```
Then, in CI, we can:
```bash
# Build Storybook
npm run build:storybook
# Run Chromatic (which will also upload the build and run its static tests)
npx chromatic --project-token $CHROMATIC_PROJECT_TOKEN --storybook-build-dir storybook-static
# Then run our Playwright tests for interactive states
npm run test:visual
```
However, note that Chromatic might run in parallel and we don't want to interfere. Also, Chromatic might clean up the build directory?
Actually, Chromatic expects the build directory to be present and then it runs its tests. We are building first and then letting Chromatic use that build.
Alternatively, we can let Chromatic build and then we run Playwright on the same build directory. But Chromatic by default builds the storybook?
Check: `chromatic` command by default runs `storybook build` if the build directory doesn't exist. We can skip that by using `--skip`?
Actually, we want to build once and use that build for both. So:
Step 1: Build storybook (so we have a build directory).
Step 2: Run Chromatic with `--storybook-build-dir` pointing to that build (and `--skip` to skip building again). But note: Chromatic might still run its own build if we don't set `--skip`?
Looking at Chromatic docs:
`--storybook-build-dir` is the directory where the built Storybook is located. Chromatic will use that and not rebuild.
So:
```bash
storybook build
chromatic --project-token $CHROMATIC_PROJECT_TOKEN --storybook-build-dir storybook-static
playwright test --baseURL=file://$(pwd)/storybook-static
```
f. Custom Diff Heuristics for Dynamic Content:
For components that have dynamic content (like a clock, or random data), we might need to ignore certain areas.
We can mask those areas before comparing. For example, if we have a component that shows the current time, we can:
- In the baseline image, we know the area where the time is. We can set those pixels to a fixed color (like black) in both baseline and current, then compare.
Alternatively, we can use `resemble.js` with an ignore option.
Example with `resemble.js`:
```javascript
resemble(baseline)
.compareTo(current)
.ignoreBox({ x: 10, y: 10, width: 100, height: 20 }) // ignore a rectangle
.onComplete(function (data) {
console.log(data);
});
```
We can define multiple ignore boxes for dynamic parts.
We can also set a threshold for color difference.
We can wrap this in a helper function and use it in our tests.
-
Considerations:
- We need to maintain baseline images for every interactive state we want to test. We can store them in a
baseline folder and reference them in tests.
- When a baseline needs to be updated (after a legitimate change), we can update the baseline by taking a new screenshot and replacing the old one. We can have a script for that.
- We might want to run the Playwright tests only on the stories that have interactive states, to save time.
-
Example Project Structure:
project/
├── .storybook/
├── stories/
├── tests/
│ ├── button.spec.ts
│ ├── baseline/
│ │ ├── button-hover.png
│ │ └── ...
│ └── diff/ (generated during test runs)
├── storybook-static/ (generated by build)
└── package.json
-
Running in CI:
We can set up a GitHub Actions workflow that:
- Checks out code.
- Sets up Node.
- Installs dependencies.
- Builds Storybook.
- Runs Chromatic (with
--exit-once-uploaded to wait for tests? Actually, Chromatic runs tests and then exits. We can wait for it to finish).
- Then runs Playwright tests (which will compare against baselines and generate new diffs if needed, and fail if above threshold).
We might want to fail the CI if either Chromatic or Playwright tests fail.
-
Updating Baselines:
We can have a separate command that updates the baseline images for the interactive states. This command would:
- Build Storybook.
- Run a Playwright test that takes screenshots for each interactive state and saves them as the new baseline.
We can mark those tests with a tag (e.g., @update-baseline) and then run only those tests with a command.
Example test for updating baseline:
test.describe('update baseline', () => {
test('button hover', async ({ page }) => {
await page.goto('/iframe.html?args=&id=button--hover');
const button = page.locator('#button-id');
await button.hover();
const screenshot = await page.screenshot();
writeFileSync(join(__dirname, 'baseline', 'button-hover.png'), screenshot);
});
});
Then run:
PLAYwright_UPDATE_BASELINE=true npx playwright test --grep @update-baseline
And in the test, conditionally update the baseline if the environment variable is set.
Alternatively, we can have a separate script that runs the tests with a flag to update.
-
Summary:
This is a complex setup. We are combining:
- Chromatic for static visual regression (and hosting Storybook).
- Playwright for interactive state testing.
- Custom image diffing with
pixelmatch or resemble.js.
We must be cautious about:
- Flakiness: interactivity might be slow, so we need proper waiting (e.g., wait for hover effect to complete). We can use
expect(...).toHaveScreenshot() from Playwright? Actually, Playwright has a built-in expect matcher for screenshots with a threshold. But we are doing custom diff.
Alternatively, we can use Playwright's expect(page).toHaveScreenshot({ maxDiffPixelRatio: 0.1 }) which uses pixelmatch under the hood and allows threshold. But note: Playwright's screenshot comparison is for the entire page. We might want to compare a specific element.
We can use:
await expect(button).toHaveScreenshot({ maxDiffPixelRatio: 0.1, threshold: 0.2 });
However, Playwright's toHaveScreenshot for an element might not be available in all versions? It is available in recent versions.
But note: Playwright's toHaveScreenshot for an element does not support masking (ignore areas). So if we have dynamic content, we might need to use the custom approach.
Alternatively, we can take a screenshot of the element, then use our custom diff with ignore areas.
Given the complexity, we might stick with our custom diff for interactive states that require masking.
-
Final Note:
This is a high-level plan. Implementation details will depend on the specific project and component structures.
We might also consider using Chromatic's --interactive flag? Actually, Chromatic does not support interactive testing natively. So we need Playwright for that.
We are essentially using Chromatic for static stories and Playwright for the rest.
We can also use Chromatic's --only-story to run a specific story, but that's for static.
So the suite:
- Static stories: Chromatic.
- Interactive states: Playwright with custom diff.
We have to maintain two sets of baselines? Not necessarily. We can use the same baseline images for both, but Chromatic and Playwright might use different image comparison algorithms. So it's better to separate.
Alternatively, we can disable Chromatic for stories that we test with Playwright? But then we lose the static test for that story.
We can have:
- For a component that has both static and interactive states, we let Chromatic test the static state (the story without interactions) and Playwright test the interactive states.
We have to make sure that the same build is used for both.
This is a viable solution.
I'll create a comprehensive Storybook visual testing suite that combines Chromatic for static snapshots, Playwright for interactive states, and custom diff heuristics for dynamic content. Here's a complete implementation:
Project Structure
visual-testing-suite/
├── .storybook/
│ ├── main.ts
│ ├── preview.ts
│ └── chromatic.ts
├── tests/
│ ├── visual/
│ │ ├── interactive-states/
│ │ │ ├── Button.hover.spec.ts
│ │ │ ├── Modal.open.spec.ts
│ │ │ └── ...
│ │ ├── fixtures/
│ │ │ ├── baselines/
│ │ │ └── thresholds.json
│ │ └── utils/
│ │ ├── custom-diff.ts
│ │ ├── screenshot-helpers.ts
│ │ └── state-matchers.ts
├── scripts/
│ ├── update-baselines.ts
│ └── ci-visual-tests.ts
├── package.json
└── playwright.config.ts
1. Package.json Setup
{
"name": "storybook-visual-testing-suite",
"scripts": {
"chromatic": "chromatic --project-token $CHROMATIC_PROJECT_TOKEN",
"test:visual": "playwright test tests/visual/",
"test:visual:update": "playwright test tests/visual/ --update-snapshots",
"test:visual:ci": "playwright test tests/visual/ --project=chromium",
"build-storybook": "storybook build"
},
"devDependencies": {
"@chromatic-com/storybook": "^1.5.0",
"@playwright/test": "^1.40.0",
"pixelmatch": "^5.3.0",
"pngjs": "^7.0.0",
"sharp": "^0.33.0",
"storybook": "^7.6.0"
}
}
2. Storybook Configuration
.storybook/main.ts
import type { StorybookConfig } from '@storybook/react-vite';
const config: StorybookConfig = {
stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
addons: [
'@chromatic-com/storybook',
'@storybook/addon-links',
'@storybook/addon-essentials',
'@storybook/addon-interactions',
],
framework: {
name: '@storybook/react-vite',
options: {},
},
docs: {
autodocs: 'tag',
},
chromatic: {
// Configure for interactive testing
disableDynamicViewport: true,
},
};
export default config;
.storybook/preview.ts
import type { Preview } from '@storybook/react';
import '../src/styles/globals.css';
const preview: Preview = {
parameters: {
actions: { argTypesRegex: '^on[A-Z].*' },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
// Configure for consistent screenshots
layout: 'centered',
viewport: { defaultViewport: 'responsive' },
},
globalTypes: {
// Custom globals for testing states
interactiveState: {
description: 'Current interactive state for testing',
defaultValue: 'default',
toolbar: {
title: 'Interactive State',
items: ['default', 'hover', 'focus', 'active', 'disabled'],
},
},
},
};
export default preview;
3. Custom Diff Utilities
tests/visual/utils/custom-diff.ts
import { PNG } from 'pngjs';
import pixelmatch from 'pixelmatch';
import sharp from 'sharp';
import fs from 'fs/promises';
import path from 'path';
export interface DiffOptions {
threshold?: number; // Pixel difference threshold (0-255)
ignoreAntialiasing?: boolean;
ignoreRegions?: Array<{ x: number; y: number; width: number; height: number }>;
maxDiffPixels?: number;
diffColor?: [number, number, number]; // RGB for diff highlight
}
export interface DiffResult {
match: boolean;
diffPercent: number;
diffPixels: number;
diffImagePath?: string;
metadata: {
width: number;
height: number;
totalPixels: number;
};
}
/**
* Custom diff algorithm with heuristics for UI testing
*/
export async function customImageDiff(
baselinePath: string,
currentPath: string,
options: DiffOptions = {}
): Promise<DiffResult> {
const {
threshold = 10,
ignoreAntialiasing = true,
ignoreRegions = [],
maxDiffPixels = 0.01, // 1% by default
diffColor = [255, 0, 0], // Red
} = options;
// Read images
const [baseline, current] = await Promise.all([
sharp(baselinePath).raw().ensureAlpha().toBuffer({ resolveWithObject: true }),
sharp(currentPath).raw().ensureAlpha().toBuffer({ resolveWithObject: true }),
]);
if (baseline.info.width !== current.info.width ||
baseline.info.height !== current.info.height) {
throw new Error(`Image dimensions don't match: ${baseline.info.width}x${baseline.info.height} vs ${current.info.width}x${current.info.height}`);
}
const { width, height } = baseline.info;
const totalPixels = width * height;
// Create diff buffer
const diffBuffer = Buffer.alloc(width * height * 4);
// Apply ignore regions by setting diff to 0 in those areas
const maskedBaseline = Buffer.from(baseline.data);
const maskedCurrent = Buffer.from(current.data);
for (const region of ignoreRegions) {
for (let y = region.y; y < region.y + region.height; y++) {
for (let x = region.x; x < region.x + region.width; x++) {
const idx = (y * width + x) * 4;
// Set alpha to 0 in ignore regions
maskedBaseline[idx + 3] = 0;
maskedCurrent[idx + 3] = 0;
}
}
}
// Calculate diff
const diffPixels = pixelmatch(
maskedBaseline,
maskedCurrent,
diffBuffer,
width,
height,
{
threshold,
includeAA: !ignoreAntialiasing,
}
);
const diffPercent = (diffPixels / totalPixels) * 100;
// Apply diff color to diff buffer
for (let i = 0; i < diffBuffer.length; i += 4) {
if (diffBuffer[i + 3] > 0) { // If there's a diff
diffBuffer[i] = diffColor[0]; // R
diffBuffer[i + 1] = diffColor[1]; // G
diffBuffer[i + 2] = diffColor[2]; // B
diffBuffer[i + 3] = 255; // A
}
}
const match = diffPercent <= (maxDiffPixels * 100);
return {
match,
diffPercent,
diffPixels,
metadata: { width, height, totalPixels },
};
}
/**
* Generate diff image for debugging
*/
export async function generateDiffImage(
baselinePath: string,
currentPath: string,
outputPath: string,
options: DiffOptions = {}
): Promise<DiffResult> {
const result = await customImageDiff(baselinePath, currentPath, options);
if (!result.match) {
// Create diff image by overlaying differences on current image
const current = await sharp(currentPath).png().toBuffer();
const { diffBuffer, width, height } = await getDiffBuffer(
baselinePath,
currentPath,
options
);
// Composite diff onto current image
const diffOverlay = await sharp(diffBuffer, {
raw: {
width,
height,
channels: 4,
},
})
.png()
.toBuffer();
await sharp(current)
.composite([{ input: diffOverlay, blend: 'over' }])
.toFile(outputPath);
result.diffImagePath = outputPath;
}
return result;
}
async function getDiffBuffer(
baselinePath: string,
currentPath: string,
options: DiffOptions
): Promise<{ diffBuffer: Buffer; width: number; height: number }> {
const [baseline, current] = await Promise.all([
sharp(baselinePath).raw().ensureAlpha().toBuffer({ resolveWithObject: true }),
sharp(currentPath).raw().ensureAlpha().toBuffer({ resolveWithObject: true }),
]);
const { width, height } = baseline.info;
const diffBuffer = Buffer.alloc(width * height * 4);
const maskedBaseline = Buffer.from(baseline.data);
const maskedCurrent = Buffer.from(current.data);
for (const region of options.ignoreRegions || []) {
for (let y = region.y; y < region.y + region.height; y++) {
for (let x = region.x; x < region.x + region.width; x++) {
const idx = (y * width + x) * 4;
maskedBaseline[idx + 3] = 0;
maskedCurrent[idx + 3] = 0;
}
}
}
pixelmatch(
maskedBaseline,
maskedCurrent,
diffBuffer,
width,
height,
{
threshold: options.threshold || 10,
includeAA: !options.ignoreAntialiasing,
}
);
return { diffBuffer, width, height };
}
tests/visual/utils/screenshot-helpers.ts
import { Page, BrowserContext } from '@playwright/test';
import path from 'path';
import fs from 'fs/promises';
export class ScreenshotHelper {
private context: BrowserContext;
private snapshotDir: string;
constructor(context: BrowserContext, snapshotDir: string) {
this.context = context;
this.snapshotDir = snapshotDir;
}
async takeStateScreenshot(
page: Page,
storyId: string,
state: string,
options: { fullPage?: boolean; selector?: string } = {}
): Promise<string> {
const { fullPage = false, selector } = options;
// Ensure directory exists
const stateDir = path.join(this.snapshotDir, storyId);
await fs.mkdir(stateDir, { recursive: true });
const screenshotPath = path.join(stateDir, `${state}.png`);
const screenshot = await page.screenshot({
path: screenshotPath,
fullPage,
animations: 'disabled',
});
return screenshotPath;
}
async applyInteractiveState(page: Page, state: string): Promise<void> {
// Use Storybook's global type to set state
await page.evaluate((testState) => {
const event = new CustomEvent('set-interactive-state', {
detail: { state: testState }
});
window.dispatchEvent(event);
}, state);
// Wait for any animations/transitions
await page.waitForTimeout(300);
}
}
tests/visual/utils/state-matchers.ts
import { test as base } from '@playwright/test';
import { customImageDiff, DiffResult } from './custom-diff';
import { ScreenshotHelper } from './screenshot-helpers';
import fs from 'fs/promises';
import path from 'path';
type TestState = 'default' | 'hover' | 'focus' | 'active' | 'disabled' | 'open' | 'closed';
export const test = base.extend<{
screenshotHelper: ScreenshotHelper;
storyId: string;
baselineDir: string;
diffDir: string;
}>({
screenshotHelper: async ({ browser }, use) => {
const context = await browser.newContext();
const snapshotDir = path.join(process.cwd(), 'tests/visual/fixtures/snapshots');
const helper = new ScreenshotHelper(context, snapshotDir);
await use(helper);
await context.close();
},
storyId: ['default-story', { option: true }],
baselineDir: async ({}, use) => {
const dir = path.join(process.cwd(), 'tests/visual/fixtures/baselines');
await fs.mkdir(dir, { recursive: true });
await use(dir);
},
diffDir: async ({}, use) => {
const dir = path.join(process.cwd(), 'tests/visual/fixtures/diffs');
await fs.mkdir(dir, { recursive: true });
await use(dir);
},
});
export async function expectStateToMatchSnapshot(
page: any,
state: TestState,
options: {
maxDiffPercent?: number;
ignoreRegions?: Array<{ x: number; y: number; width: number; height: number }>;
threshold?: number;
} = {}
): Promise<DiffResult> {
const {
maxDiffPercent = 0.1, // 0.1% default tolerance
ignoreRegions = [],
threshold = 10,
} = options;
const storyId = page.storyId || 'unknown-story';
const baselinePath = path.join(
process.cwd(),
'tests/visual/fixtures/baselines',
`${storyId}.${state}.png`
);
const currentPath = await page.screenshotHelper.takeStateScreenshot(
page,
storyId,
state
);
// Check if baseline exists
const baselineExists = await fs.access(baselinePath).then(() => true).catch(() => false);
if (!baselineExists) {
throw new Error(`Baseline not found for ${storyId} in state ${state}. Run with --update-snapshots to create.`);
}
const diffResult = await customImageDiff(baselinePath, currentPath, {
threshold,
ignoreRegions,
maxDiffPixels: maxDiffPercent / 100,
});
if (!diffResult.match) {
const diffPath = path.join(
process.cwd(),
'tests/visual/fixtures/diffs',
`${storyId}.${state}-diff.png`
);
await generateDiffImage(baselinePath, currentPath, diffPath, {
threshold,
ignoreRegions,
});
throw new Error(
`Visual mismatch for ${storyId} (state: ${state})\n` +
`Diff: ${diffResult.diffPercent.toFixed(2)}% (threshold: ${maxDiffPercent}%)\n` +
`See diff at: ${diffPath}`
);
}
return diffResult;
}
4. Interactive State Test Example
tests/visual/interactive-states/Button.hover.spec.ts
import { test, expect } from './utils/state-matchers';
import { expectStateToMatchSnapshot } from './utils/state-matchers';
test.describe('Button Component - Interactive States', () => {
test.beforeEach(async ({ page }) => {
// Navigate to Storybook and load specific story
await page.goto('/iframe.html?id=button--primary');
await page.waitForLoadState('networkidle');
});
test('default state matches baseline', async ({ page }) => {
await expectStateToMatchSnapshot(page, 'default', {
maxDiffPercent: 0.1,
});
});
test('hover state matches baseline', async ({ page, screenshotHelper }) => {
const button = page.locator('[data-testid="button-primary"]');
// Apply hover state
await button.hover();
await expectStateToMatchSnapshot(page, 'hover', {
maxDiffPercent: 0.2, // Allow slightly more for antialiasing
ignoreRegions: [
// Ignore dynamic cursor position if visible
{ x: 0, y: 0, width: 32, height: 32 },
],
});
});
test('focus-within state matches baseline', async ({ page }) => {
const button = page.locator('[data-testid="button-primary"]');
await button.focus();
await page.keyboard.press('Tab'); // Simulate focus-within
await expectStateToMatchSnapshot(page, 'focus', {
maxDiffPercent: 0.15,
});
});
test('disabled state matches baseline', async ({ page }) => {
// Navigate to disabled story variant
await page.goto('/iframe.html?id=button--disabled');
await expectStateToMatchSnapshot(page, 'disabled', {
maxDiffPercent: 0.1,
});
});
});
tests/visual/interactive-states/Modal.open.spec.ts
import { test } from './utils/state-matchers';
test.describe('Modal Component - Interactive States', () => {
test('closed state matches baseline', async ({ page }) => {
await page.goto('/iframe.html?id=modal--default');
await expectStateToMatchSnapshot(page, 'closed', {
maxDiffPercent: 0.05,
});
});
test('open state matches baseline', async ({ page }) => {
await page.goto('/iframe.html?id=modal--default');
// Open modal
const openButton = page.locator('[data-testid="open-modal-button"]');
await openButton.click();
// Wait for animation
await page.waitForTimeout(400);
await expectStateToMatchSnapshot(page, 'open', {
maxDiffPercent: 0.1,
ignoreRegions: [
// Ignore backdrop blur variations
{ x: 0, y: 0, width: 1200, height: 10 },
],
});
});
test('modal with dynamic content', async ({ page }) => {
await page.goto('/iframe.html?id=modal--dynamic');
// Open modal
await page.locator('[data-testid="open-modal"]').click();
await page.waitForTimeout(300);
// Set timestamp to predictable value for comparison
await page.evaluate(() => {
const now = new Date('2024-01-01T12:00:00Z');
// Mock date in your component
window.mockDate = now;
});
await expectStateToMatchSnapshot(page, 'open-with-timestamp', {
maxDiffPercent: 0.2,
threshold: 20, // Higher threshold for text rendering differences
});
});
});
5. CI/CD Integration Script
scripts/ci-visual-tests.ts
#!/usr/bin/env node
import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
const STORYBOOK_BUILD_DIR = 'storybook-static';
const CHROMATIC_PROJECT_TOKEN = process.env.CHROMATIC_PROJECT_TOKEN;
if (!CHROMATIC_PROJECT_TOKEN) {
console.error('CHROMATIC_PROJECT_TOKEN is required');
process.exit(1);
}
console.log('🚀 Starting visual testing pipeline...');
// Step 1: Build Storybook
console.log('📦 Building Storybook...');
execSync('npx storybook build', { stdio: 'inherit' });
// Step 2: Run Chromatic for static snapshots
console.log('🎨 Running Chromatic for static visual tests...');
try {
execSync(
`npx chromatic --project-token=${CHROMATIC_PROJECT_TOKEN} --storybook-build-dir=${STORYBOOK_BUILD_DIR} --exit-once-uploaded`,
{ stdio: 'inherit' }
);
} catch (error) {
console.error('❌ Chromatic tests failed');
process.exit(1);
}
// Step 3: Run Playwright interactive tests
console.log('🖱️ Running Playwright interactive state tests...');
try {
execSync('npx playwright test tests/visual/ --project=chromium', {
stdio: 'inherit',
env: {
...process.env,
STORYBOOK_BUILD_DIR: path.join(process.cwd(), STORYBOOK_BUILD_DIR),
}
});
} catch (error) {
console.error('❌ Playwright interactive tests failed');
process.exit(1);
}
// Step 4: Generate visual test report
console.log('📊 Generating visual test report...');
generateReport();
console.log('✅ Visual testing pipeline completed successfully!');
function generateReport() {
const diffDir = 'tests/visual/fixtures/diffs';
const diffFiles = fs.readdirSync(diffDir).filter(f => f.endsWith('-diff.png'));
if (diffFiles.length > 0) {
console.warn(`\n⚠️ Found ${diffFiles.length} visual differences:`);
diffFiles.forEach(file => {
console.log(` - ${file}`);
});
console.log('\nReview diffs in tests/visual/fixtures/diffs/');
}
// Could generate HTML report here
const reportPath = path.join(process.cwd(), 'visual-test-report.html');
const html = `
<!DOCTYPE html>
<html>
<head>
<title>Visual Test Report</title>
<style>
body { font-family: system-ui; padding: 20px; }
.diff { margin: 20px 0; }
img { max-width: 100%; border: 1px solid #ddd; }
</style>
</head>
<body>
<h1>Visual Test Report</h1>
<p>Generated: ${new Date().toISOString()}</p>
<h2>Differences Found: ${diffFiles.length}</h2>
${diffFiles.map(file => `
<div class="diff">
<h3>${file}</h3>
<img src="../${diffDir}/${file}" alt="Diff for ${file}">
</div>
`).join('')}
</body>
</html>
`;
fs.writeFileSync(reportPath, html);
console.log(`📄 HTML report generated: ${reportPath}`);
}
6. Playwright Configuration
playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 1 : 0,
workers: process.env.CI ? 2 : undefined,
reporter: 'html',
use: {
// Use built Storybook from Chromatic
baseURL: `file://${process.env.STORYBOOK_BUILD_DIR || './storybook-static'}`,
trace: 'on-first-retry',
screenshot: 'only-on-failure',
viewport: { width: 1280, height: 720 },
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
],
// Global setup for visual testing
globalSetup: require.resolve('./tests/visual/global-setup.ts'),
// Global teardown
globalTeardown: require.resolve('./tests/visual/global-teardown.ts'),
});
tests/visual/global-setup.ts
import { chromium, FullConfig } from '@playwright/test';
export default async function globalSetup(config: FullConfig) {
// Ensure baseline directories exist
const fs = require('fs');
const dirs = [
'tests/visual/fixtures/baselines',
'tests/visual/fixtures/diffs',
'tests/visual/fixtures/snapshots',
];
dirs.forEach(dir => {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
});
// Optional: Start Storybook server if not using static build
if (!process.env.STORYBOOK_BUILD_DIR) {
console.log('Starting Storybook server for visual tests...');
// Start Storybook dev server
const { spawn } = require('child_process');
const storybook = spawn('npx', ['storybook', 'dev', '--port', '6006'], {
stdio: 'inherit',
detached: true,
});
// Store PID for cleanup
fs.writeFileSync('.storybook-pid', storybook.pid.toString());
// Wait for Storybook to be ready
await new Promise(resolve => setTimeout(resolve, 10000));
}
}
7. Update Baselines Script
scripts/update-baselines.ts
#!/usr/bin/env node
import { chromium, test as base } from '@playwright/test';
import path from 'path';
import fs from 'fs/promises';
import { ScreenshotHelper } from '../tests/visual/utils/screenshot-helpers';
const STORIES = [
{ id: 'button--primary', states: ['default', 'hover', 'focus', 'active'] },
{ id: 'button--disabled', states: ['disabled'] },
{ id: 'modal--default', states: ['closed', 'open'] },
// Add more stories...
];
async function updateBaselines() {
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
const snapshotDir = path.join(process.cwd(), 'tests/visual/fixtures/baselines');
await fs.mkdir(snapshotDir, { recursive: true });
const helper = new ScreenshotHelper(context, snapshotDir);
console.log('🔄 Updating visual baselines...');
for (const story of STORIES) {
console.log(`\n📸 Updating ${story.id}`);
await page.goto(`/iframe.html?id=${story.id}`);
await page.waitForLoadState('networkidle');
for (const state of story.states) {
try {
// Apply state (customize based on your component's interaction)
await applyState(page, state);
await page.waitForTimeout(300); // Wait for transitions
await helper.takeStateScreenshot(page, story.id, state);
console.log(` ✓ ${state}`);
} catch (error) {
console.error(` ✗ ${state}: ${error.message}`);
}
}
}
await context.close();
await browser.close();
console.log('\n✅ Baselines updated successfully!');
}
async function applyState(page: any, state: string): Promise<void> {
switch (state) {
case 'hover':
const button = page.locator('[data-testid="button-primary"]');
await button.hover();
break;
case 'focus':
await page.locator('[data-testid="button-primary"]').focus();
break;
case 'open':
await page.locator('[data-testid="open-modal-button"]').click();
break;
case 'closed':
// Modal might be closed by default
break;
default:
// Default state, no action needed
break;
}
}
updateBaselines().catch(console.error);
8. Storybook Custom Parameters for Testing
Add to your component stories:
// Example: Button.stories.tsx
import type { Meta, StoryObj } from '@storybook/react';
const meta: Meta<typeof Button> = {
title: 'Components/Button',
component: Button,
parameters: {
// Add testing-specific parameters
chromatic: {
// Exclude from static Chromatic tests if only testing interactivity
// modes: ['DISABLE_MODE'], // Uncomment to skip static tests
diffThreshold: 0.01,
},
// Custom testing annotations
test: {
// States to test interactively
interactiveStates: ['default', 'hover', 'focus', 'active', 'disabled'],
// Regions to ignore in diffs (e.g., dynamic timestamps)
ignoreRegions: [
{ x: 100, y: 10, width: 200, height: 30 }, // Timestamp area
],
},
},
};
export default meta;
type Story = StoryObj<typeof Button>;
export const Primary: Story = {
args: {
variant: 'primary',
children: 'Click me',
},
play: async ({ canvasElement }) => {
// Optional: Add Playwright interactions for Chromatic
const canvas = await import('@playwright/test').then(m => m);
const page = canvasElement.ownerDocument.defaultView;
// Your interactions...
},
};
9. GitHub Actions Workflow
.github/workflows/visual-tests.yml
name: Visual Regression Tests
on:
push:
branches: [main, develop]
pull_request:
jobs:
visual-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm ci
- name: Build Storybook
run: npm run build-storybook
- name: Run Chromatic
run: npx chromatic --project-token=${{ secrets.CHROMATIC_PROJECT_TOKEN }} --storybook-build-dir=storybook-static --exit-once-uploaded
env:
CHROMATIC_PROJECT_TOKEN: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
- name: Run Playwright Interactive Tests
run: npm run test:visual:ci
env:
STORYBOOK_BUILD_DIR: ${{ github.workspace }}/storybook-static
- name: Upload visual diffs
if: always()
uses: actions/upload-artifact@v3
with:
name: visual-diffs
path: tests/visual/fixtures/diffs/
- name: Upload HTML report
if: always()
uses: actions/upload-artifact@v3
with:
name: visual-report
path: visual-test-report.html
10. Usage Examples
Basic usage:
# Run all visual tests
npm run test:visual
# Update baselines (after intentional changes)
npm run test:visual:update
# Run in CI mode
npm run test:visual:ci
# Full pipeline (Chromatic + Playwright)
npm run chromatic && npm run test:visual
Custom thresholds for specific components:
test('complex chart with dynamic data', async ({ page }) => {
await page.goto('/iframe.html?id=chart--dynamic');
// Set predictable data for test
await page.evaluate(() => {
window.setTestData([10, 20, 30, 40]);
});
await expectStateToMatchSnapshot(page, 'rendered', {
maxDiffPercent: 0.5, // Charts may have more variance
threshold: 15,
ignoreRegions: [
// Ignore axis labels that might render slightly differently
{ x: 0, y: 0, width: 50, height: 400 },
],
});
});
Key Features:
- Hybrid approach: Chromatic for static stories + Playwright for interactivity
- Custom diff heuristics: Pixel-level comparison with configurable thresholds and region exclusion
- State management: Explicit state testing (hover, focus, disabled, etc.)
- CI/CD ready: Full pipeline with artifact uploads
- Dynamic content handling: Region masking for timestamps, random data, etc.
- Diff visualization: Generate highlighted diff images
- Baseline management: Simple update workflow
- Cross-browser: Test in multiple browsers
- Smart selectors: Use
data-testid for reliable element targeting
- Reporting: HTML report generation with diff images
This setup provides production-ready visual testing that handles both static and interactive states with customizable sensitivity for different component types.