Testing Design System Components: Accessibility, Theming, and Visual Regression

Testing Design System Components: Accessibility, Theming, and Visual Regression

A design system is a contract between design and engineering. When a Button component changes, it changes everywhere. When a color token shifts, it shifts across the entire product. Without automated tests, design system releases are terrifying — a one-line change to a shared utility can visually break hundreds of components.

This guide covers a complete testing strategy for design system components: accessibility checking, theme variant testing, responsive breakpoints, and visual regression — all integrated into a CI pipeline.

Why Design Systems Need Automated Testing

Design systems have a unique testing challenge: the components themselves are often simple (a button, a card, a text input), but they're used in dozens of contexts and must work correctly across:

  • Multiple themes (light/dark mode, brand variants)
  • Multiple breakpoints (mobile, tablet, desktop)
  • Multiple states (default, hover, focus, active, disabled, loading, error)
  • Accessibility requirements (screen readers, keyboard navigation, color contrast)

Manual testing all of this before every release is impractical. Automated tests catch regressions early and give designers confidence that their tokens are rendering correctly.

Setting Up Storybook for a Design System

Storybook is the natural home for design system documentation. The testing strategy builds on top of it.

npx storybook@latest init
npm install --save-dev @storybook/addon-a11y @storybook/test chromatic

Configure addons:

// .storybook/main.js
module.exports = {
  addons: [
    '@storybook/addon-essentials',
    '@storybook/addon-a11y',
    '@storybook/addon-interactions',
    '@storybook/addon-themes',
  ],
  framework: '@storybook/react-vite',
};

Accessibility Testing with storybook-addon-a11y

The @storybook/addon-a11y addon runs axe-core on every story and shows accessibility violations in the Accessibility panel. It catches:

  • Missing alt text on images
  • Insufficient color contrast
  • Missing form labels
  • Improper ARIA attributes
  • Keyboard navigation issues
// .storybook/preview.js
import { withA11y } from '@storybook/addon-a11y';

export const decorators = [withA11y];

export const parameters = {
  a11y: {
    // Configure which axe rules to run
    config: {
      rules: [
        {
          // Enforce WCAG 2.1 AA color contrast
          id: 'color-contrast',
          enabled: true,
        },
      ],
    },
    // Configure per-element options
    options: {
      runOnly: {
        type: 'tag',
        values: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'],
      },
    },
  },
};

To disable a11y for a specific story (e.g., a decorative example):

export const DecorativeExample: Story = {
  parameters: {
    a11y: { disable: true },
  },
};

Automated Accessibility Testing with axe-playwright

The Storybook addon shows violations in the UI, but you also want to fail CI on accessibility violations. Use the test runner with axe-playwright:

npm install --save-dev @storybook/test-runner axe-playwright
// .storybook/test-runner.js
const { injectAxe, checkA11y } = require('axe-playwright');

module.exports = {
  async preVisit(page) {
    await injectAxe(page);
  },

  async postVisit(page, context) {
    await checkA11y(page, '#storybook-root', {
      detailedReport: true,
      detailedReportOptions: {
        html: true,
      },
      // Fail on critical and serious violations only
      includedImpacts: ['critical', 'serious'],
    });
  },
};

With this setup, CI fails if any story has a critical or serious axe violation. You get the full axe report as output, including the specific DOM element and suggested fix.

For components that have known acceptable violations (e.g., a demonstration of inaccessible patterns in a "don't do this" story):

export const InaccessibleExample: Story = {
  parameters: {
    a11y: {
      config: {
        rules: [{ id: 'color-contrast', enabled: false }],
      },
    },
  },
};

Theme Variant Testing

Design systems often support multiple themes. Test that components render correctly in each:

// .storybook/preview.tsx
import { withThemeByClassName } from '@storybook/addon-themes';

export const decorators = [
  withThemeByClassName({
    themes: {
      light: 'theme-light',
      dark: 'theme-dark',
      'high-contrast': 'theme-high-contrast',
    },
    defaultTheme: 'light',
  }),
];

Write stories that explicitly test dark mode:

// src/components/Button/Button.stories.tsx
export const DarkMode: Story = {
  parameters: {
    themes: { themeOverride: 'dark' },
    chromatic: {
      // Capture both light and dark in CI
      modes: {
        light: { theme: 'light' },
        dark: { theme: 'dark' },
      },
    },
  },
};

With Chromatic's modes, it captures a separate snapshot for each theme combination. A change to a CSS color token appears in both the light and dark mode snapshots — you review both before accepting.

For CSS custom property-based theming:

// Test that the component respects CSS variables
export const BrandVariants: Story = {
  render: () => (
    <div style={{ display: 'flex', gap: '16px' }}>
      <div style={{ '--brand-primary': '#3B82F6', '--brand-text': '#1E3A8A' }}>
        <Button variant="primary">Blue Brand</Button>
      </div>
      <div style={{ '--brand-primary': '#10B981', '--brand-text': '#064E3B' }}>
        <Button variant="primary">Green Brand</Button>
      </div>
    </div>
  ),
};

Responsive Component Testing

Test that components render correctly at different breakpoints:

// Configure viewport testing in Storybook
export const MobileView: Story = {
  parameters: {
    viewport: {
      defaultViewport: 'mobile1',
    },
    chromatic: {
      viewports: [375, 768, 1280],
    },
  },
};

For components with responsive breakpoints:

// src/components/NavigationBar/NavigationBar.stories.tsx
export const MobileNav: Story = {
  parameters: {
    viewport: { defaultViewport: 'mobile1' },
    chromatic: {
      viewports: [375],
    },
  },
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);

    // On mobile, hamburger menu should be visible
    await expect(canvas.getByRole('button', { name: /menu/i })).toBeVisible();

    // Nav links should be hidden initially
    await expect(canvas.queryByRole('navigation')).not.toBeVisible();

    // Open the menu
    await userEvent.click(canvas.getByRole('button', { name: /menu/i }));

    // Navigation should now be visible
    await expect(canvas.getByRole('navigation')).toBeVisible();
  },
};

export const DesktopNav: Story = {
  parameters: {
    viewport: { defaultViewport: 'desktop' },
    chromatic: {
      viewports: [1280],
    },
  },
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);

    // On desktop, hamburger is hidden
    await expect(canvas.queryByRole('button', { name: /menu/i })).not.toBeInTheDocument();

    // All nav links are directly visible
    await expect(canvas.getByRole('navigation')).toBeVisible();
  },
};

Component State Matrix

For design system components, you want stories for every state combination. Create a matrix story:

// src/components/Button/Button.stories.tsx
import { Button } from './Button';

const variants = ['primary', 'secondary', 'ghost', 'danger'] as const;
const sizes = ['sm', 'md', 'lg'] as const;

export const AllVariants: Story = {
  render: () => (
    <div style={{ display: 'grid', gap: '16px' }}>
      {variants.map(variant => (
        <div key={variant} style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
          {sizes.map(size => (
            <Button key={size} variant={variant} size={size}>
              {variant} {size}
            </Button>
          ))}
          <Button variant={variant} disabled>Disabled</Button>
          <Button variant={variant} loading>Loading</Button>
        </div>
      ))}
    </div>
  ),
  parameters: {
    chromatic: { viewports: [1280] },
  },
};

This gives Chromatic a single snapshot that covers the full button matrix. Any change to any variant/size combination shows up in one diff.

Visual Regression for Component Library Releases

When cutting a new version of your design system package, visual regression testing ensures you haven't unintentionally changed existing components.

Tag each release in Chromatic:

# .github/workflows/release.yml
- name: Publish Storybook to Chromatic (release)
  uses: chromaui/action@latest
  with:
    projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
    autoAcceptChanges: false  # All changes must be reviewed for releases
    storybookBuildDir: storybook-static
    exitOnceUploaded: false
    onlyChanged: false  # Full snapshot on releases, not TurboSnap

For PRs that are non-breaking (documentation changes, new stories for new components), use --only-changed to save snapshots. For release branches, run full snapshots with no auto-acceptance.

CI Strategy

A complete CI pipeline for a design system:

# .github/workflows/design-system-ci.yml
name: Design System CI

on:
  push:
    branches: [main, 'release/**']
  pull_request:

jobs:
  unit-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '20', cache: 'npm' }
      - run: npm ci
      - run: npm test

  storybook-build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '20', cache: 'npm' }
      - run: npm ci
      - run: npm run build-storybook
      - uses: actions/upload-artifact@v4
        with:
          name: storybook-static
          path: storybook-static
          retention-days: 1

  accessibility-tests:
    needs: storybook-build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '20', cache: 'npm' }
      - run: npm ci
      - uses: actions/download-artifact@v4
        with: { name: storybook-static, path: storybook-static }
      - name: Install Playwright
        run: npx playwright install --with-deps chromium
      - name: Run accessibility tests
        run: |
          npx concurrently -k -s first -n "SB,TEST" \
            "npx http-server storybook-static -p 6006 --silent" \
            "npx wait-on tcp:6006 && npx test-storybook --ci"

  visual-regression:
    needs: storybook-build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with: { fetch-depth: 0 }
      - uses: actions/setup-node@v4
        with: { node-version: '20', cache: 'npm' }
      - run: npm ci
      - uses: actions/download-artifact@v4
        with: { name: storybook-static, path: storybook-static }
      - name: Chromatic visual regression
        uses: chromaui/action@latest
        with:
          projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
          storybookBuildDir: storybook-static
          onlyChanged: ${{ github.ref != 'refs/heads/main' }}
          exitZeroOnChanges: ${{ github.ref != 'refs/heads/main' }}

This pipeline:

  1. Runs unit tests independently (fast, no browser needed)
  2. Builds Storybook once and uploads as an artifact
  3. Runs accessibility tests against the built Storybook
  4. Runs visual regression against the built Storybook
  5. On main branch: full snapshots, fail on unreviewed changes
  6. On PRs: TurboSnap only changed stories, don't fail CI on visual changes (require review)

Versioning and Breaking Change Detection

For design systems that publish to npm, combine visual regression with semantic versioning:

  • Visual changes accepted in Chromatic → at minimum a patch version
  • New component or new props added → minor version
  • Props removed or renamed, CSS tokens removed → major version

Automate this with changesets:

npm install --save-dev @changesets/cli
npx changeset init

Require a changeset in CI for all PRs that touch component files:

- name: Check for changeset
  run: npx changeset status --since=origin/main

Combined with Chromatic visual diffs, you get a complete picture of what changed in each release: both the visual output (via Chromatic) and the semantic intent (via changeset descriptions).

Read more

Start now free