Visual Regression Testing Across Dark Mode and Multiple Themes
Dark mode is no longer optional. Most design systems today ship with light and dark themes at minimum, and many support additional brand themes or high-contrast accessibility modes. Each theme is an independent visual surface that can break independently — a color token that looks correct in light mode can be invisible in dark mode, a border that works with a blue theme can clash with a green theme.
Visual regression testing across themes means capturing screenshots of every component in every theme and detecting pixel-level changes. Getting this right requires thoughtful setup: how you switch themes in Storybook, how you capture per-theme screenshots, and how you prevent CI from spending ten minutes on screenshots that haven't changed.
The Core Challenge
Visual regression tools take a screenshot and compare it to a previously approved baseline. With multiple themes, you need a baseline per theme, and you need a way to render components in each theme before capturing.
The simplest approach — clicking a theme toggle and taking a screenshot — doesn't scale and doesn't work in headless CI. You need a programmatic way to render a component in theme A, capture it, then render the same component in theme B, capture it, and compare both against their respective baselines.
Setting Up storybook-dark-mode Addon
The storybook-dark-mode addon adds a toolbar button that toggles between light and dark mode, and synchronizes with the user's system preference:
npm install --save-dev storybook-dark-mode// .storybook/main.ts
const config: StorybookConfig = {
addons: [
'@storybook/addon-essentials',
'storybook-dark-mode',
],
};Configure the themes in .storybook/preview.ts:
// .storybook/preview.ts
import { themes } from '@storybook/theming';
const preview = {
parameters: {
darkMode: {
// Override the default dark theme
dark: { ...themes.dark, appBg: '#1a1a2e', barBg: '#16213e' },
// Override the default light theme
light: { ...themes.light, appBg: '#f8f9fa' },
// Which theme to start with
current: 'light',
// Apply class to the HTML element instead of Storybook's panel
classTarget: 'html',
// The class name to apply
darkClass: 'dark',
lightClass: 'light',
// Sync with system preference
stylePreview: true,
},
},
};The classTarget: 'html' and darkClass: 'dark' settings tell the addon to apply a dark class to the <html> element, which is the standard approach for CSS custom property-based theming.
CSS Custom Properties for Theme-Safe Styles
Components that use CSS custom properties (variables) for colors and spacing are inherently theme-safe — change the variable values per theme, and every component using those variables updates automatically:
/* tokens.css */
:root,
.light {
--color-background: #ffffff;
--color-surface: #f8f9fa;
--color-text-primary: #1a1a1a;
--color-text-secondary: #6b7280;
--color-border: #e5e7eb;
--color-accent: #3b82f6;
--color-accent-hover: #2563eb;
--shadow-card: 0 1px 3px rgba(0, 0, 0, 0.12);
}
.dark {
--color-background: #0f172a;
--color-surface: #1e293b;
--color-text-primary: #f1f5f9;
--color-text-secondary: #94a3b8;
--color-border: #334155;
--color-accent: #60a5fa;
--color-accent-hover: #93c5fd;
--shadow-card: 0 1px 3px rgba(0, 0, 0, 0.4);
}A component that uses these tokens:
.card {
background: var(--color-surface);
border: 1px solid var(--color-border);
color: var(--color-text-primary);
box-shadow: var(--shadow-card);
}Will automatically render correctly in both themes. Visual regression testing then catches regressions if someone changes a token value — the screenshot will differ from the baseline.
Rendering Stories in Multiple Themes
To capture screenshots in multiple themes, you need each theme rendered as a separate story or a separate viewport. There are two approaches:
Approach 1: Theme Decorator
Wrap each story (or all stories via a global decorator) to render it in both themes side by side:
// .storybook/decorators/ThemeDecorator.tsx
import React from 'react';
import '../tokens.css';
export const WithBothThemes = (Story: React.ComponentType) => (
<div style={{ display: 'flex', gap: '2rem' }}>
<div className="light" style={{ padding: '1rem', background: 'var(--color-background)' }}>
<Story />
</div>
<div className="dark" style={{ padding: '1rem', background: 'var(--color-background)' }}>
<Story />
</div>
</div>
);Apply globally in preview.ts to see both themes in every story.
Approach 2: Explicit Theme Stories
Create dedicated stories for each theme. This gives you separate baseline images per theme and clearer failure attribution:
// Button.stories.ts
export const LightTheme: Story = {
decorators: [
(Story) => (
<div className="light" style={{ padding: '1rem', background: 'var(--color-background)' }}>
<Story />
</div>
),
],
};
export const DarkTheme: Story = {
decorators: [
(Story) => (
<div className="dark" style={{ padding: '1rem', background: 'var(--color-background)' }}>
<Story />
</div>
),
],
};This creates two independently-tracked visual baselines. A regression in dark mode fails the DarkTheme story without touching the LightTheme story, making it immediately clear which theme broke.
Chromatic's Theme Matrix
If you use Chromatic for visual review, it has built-in support for testing stories across multiple theme contexts using the modes feature:
// .storybook/preview.ts
export const globalTypes = {
theme: {
name: 'Theme',
defaultValue: 'light',
toolbar: {
items: ['light', 'dark', 'high-contrast'],
},
},
};
// Chromatic modes configuration in a component story:
export const Default: Story = {
parameters: {
chromatic: {
modes: {
light: { theme: 'light' },
dark: { theme: 'dark' },
'high-contrast': { theme: 'high-contrast' },
},
},
},
};With this configuration, Chromatic will render the Default story three times — once in each mode — and track separate baselines for each. A UI change in dark mode only requires approval of the dark mode screenshot, not the light mode one.
For large component libraries, you might not want to run all modes on all stories. Apply modes globally only for your most theme-sensitive components (cards, navigation, form elements), and use the default single-mode testing for simpler components.
Playwright Multi-Theme Screenshot Capture
For teams not using Chromatic, Playwright can capture per-theme screenshots directly. This approach works with any visual comparison tool, including custom ones:
// tests/visual/themes.spec.ts
import { test, expect } from '@playwright/test';
const themes = ['light', 'dark', 'high-contrast'];
const storiesUnderTest = [
{ name: 'Button/Primary', url: '/iframe.html?id=components-button--primary' },
{ name: 'Card/Default', url: '/iframe.html?id=components-card--default' },
{ name: 'Form/Login', url: '/iframe.html?id=components-form--login' },
];
for (const theme of themes) {
test.describe(`Theme: ${theme}`, () => {
test.beforeEach(async ({ page }) => {
// Set the theme via localStorage (adjust to your implementation)
await page.addInitScript((t) => {
window.localStorage.setItem('storybook-theme', t);
}, theme);
});
for (const story of storiesUnderTest) {
test(`${story.name} in ${theme} theme`, async ({ page }) => {
await page.goto(`http://localhost:6006${story.url}`);
// Wait for component to finish rendering
await page.waitForSelector('#storybook-root [data-loaded]');
// Apply theme class if needed
await page.evaluate((t) => {
document.documentElement.className = t;
}, theme);
// Give CSS transitions time to complete
await page.waitForTimeout(300);
await expect(page).toHaveScreenshot(`${story.name}-${theme}.png`, {
threshold: 0.01, // 1% pixel difference tolerance
});
});
}
});
}Playwright's built-in toHaveScreenshot stores baseline images alongside the test files and diffs them on subsequent runs. Failed screenshots are saved to a test-results/ directory with side-by-side comparison images.
Handling CSS Transitions and Animations
CSS transitions between themes — the fade from light to dark — cause screenshot flakiness. The screenshot might capture a component mid-transition with colors between the two themes.
Disable transitions for visual testing:
/* Add to your Storybook preview with a parameter-controlled class */
.disable-transitions *,
.disable-transitions *::before,
.disable-transitions *::after {
animation-duration: 0ms !important;
transition-duration: 0ms !important;
}In Playwright, inject this class before taking screenshots:
await page.addStyleTag({
content: `
* {
animation: none !important;
transition: none !important;
}
`,
});Testing Specific Theme Regressions
Some theme-specific bugs are subtle: an icon that uses currentColor and renders correctly in light mode but disappears against a dark background, a focus ring that is invisible in dark mode, a loading skeleton that has the same color as the page background in high-contrast mode.
Create specific stories targeting these failure modes:
// Icon.stories.ts
export const DarkModeVisibility: Story = {
name: 'Dark Mode — Icon should be visible',
decorators: [
(Story) => (
<div
className="dark"
style={{
padding: '2rem',
background: 'var(--color-background)',
}}
>
<Story />
</div>
),
],
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const icon = canvas.getByRole('img', { hidden: true });
// Assert the icon is actually visible (not hidden behind background)
const styles = getComputedStyle(icon);
const fill = styles.fill || styles.color;
// The fill should not match the background color
expect(fill).not.toBe('rgb(15, 23, 42)'); // dark background color
},
};Setting Up CI for Multi-Theme Tests
GitHub Actions workflow for Playwright theme screenshot tests:
# .github/workflows/visual-tests.yml
name: Visual Regression Tests
on:
pull_request:
jobs:
visual:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- name: Install Playwright
run: npx playwright install --with-deps chromium
- name: Build Storybook
run: npm run build-storybook
- name: Run visual tests
run: |
npx serve storybook-static --port 6006 &
npx wait-on http://localhost:6006
npx playwright test tests/visual/
- name: Upload diff artifacts
if: failure()
uses: actions/upload-artifact@v4
with:
name: visual-diffs
path: test-results/Updating Baselines
When you intentionally change a component's appearance (a design update, a new token value), your baseline images will be outdated and tests will fail. Update them:
# Playwright — regenerate all screenshots
npx playwright test --update-snapshots
# Or update a specific test file
npx playwright test tests/visual/themes.spec.ts --update-snapshotsAfter updating, commit the new baseline images. They are source of truth for what the component should look like. A pull request that updates baseline images makes the visual change explicit and reviewable.
Preventing Theme Regressions Long-Term
The key insight with multi-theme visual testing is that you are testing a property of your entire design system — the consistency and correctness of your token definitions. When tokens are wrong, every component that uses them will fail simultaneously. That's actually useful signal: a widespread failure means a token changed, a targeted failure means a specific component has a theme-specific bug.
Build your visual testing suite to cover your highest-traffic components thoroughly — navigation, forms, buttons, cards — and extend coverage incrementally as you catch regressions in other areas.
For continuously monitoring your live application's visual and functional behavior across themes and real-world conditions, HelpMeTest provides ongoing test execution against your deployed site. This catches the class of theme regressions that only appear in production — browser rendering differences, system dark mode interactions, or third-party component theme conflicts that don't show up in Storybook isolation.