Accessibility Testing in Storybook: @storybook/addon-a11y and axe Integration

Accessibility Testing in Storybook: @storybook/addon-a11y and axe Integration

Accessibility testing at the component level is one of the most cost-effective things you can do for your application's accessibility posture. Catching a missing label or insufficient color contrast in a component that gets used 50 times across your application is far cheaper than finding it in a manual audit or user report.

Storybook's @storybook/addon-a11y runs axe-core against every story automatically. Every component variant you've already documented becomes an accessibility test. This post covers the setup, how to write accessibility-aware stories, how to configure axe rules, and how to make accessibility checks fail your CI build.

Installing @storybook/addon-a11y

npm install --save-dev @storybook/addon-a11y

Add it to your Storybook config:

// .storybook/main.ts
import type { StorybookConfig } from '@storybook/react-vite';

const config: StorybookConfig = {
  addons: [
    '@storybook/addon-essentials',
    '@storybook/addon-a11y',
  ],
};

export default config;

That's the entire setup. Reload Storybook and open any story — you'll see an "Accessibility" panel in the addons area at the bottom. It shows violations, incomplete checks (things axe couldn't fully determine), and passes.

What axe-core Checks

axe-core is the underlying engine. In Storybook's default configuration it runs WCAG 2.0 and 2.1 Level A and AA rules. Common violations it catches automatically:

  • Missing form labels: <input> without an associated <label> or aria-label
  • Insufficient color contrast: text that doesn't meet 4.5:1 ratio (normal text) or 3:1 ratio (large text)
  • Images without alt text: <img> without alt attribute
  • Missing button content: <button> with no text or accessible name
  • Incorrect ARIA roles: using roles that aren't valid for the element type
  • Keyboard trap: interactive elements that can't be reached by keyboard
  • Duplicate IDs: multiple elements with the same id in the document

For a form component, axe will immediately flag any input that doesn't have an accessible name, any submit button without text, and any contrast issues in placeholder text.

Writing Accessibility-Aware Stories

The a11y addon runs against whatever is rendered in the story. Your stories should cover the full range of visual states because each state can have different accessibility characteristics.

// TextField.stories.tsx
import type { Meta, StoryObj } from '@storybook/react';
import { TextField } from './TextField';

const meta: Meta<typeof TextField> = {
  component: TextField,
  title: 'Forms/TextField',
};

export default meta;
type Story = StoryObj<typeof TextField>;

// This will PASS the a11y check — has a label
export const WithLabel: Story = {
  args: {
    label: 'Email address',
    placeholder: 'you@example.com',
  },
};

// This will FAIL — no label
export const WithoutLabel: Story = {
  args: {
    placeholder: 'you@example.com',
  },
};

// Error state — check that error message is associated with input
export const WithError: Story = {
  args: {
    label: 'Email address',
    value: 'not-an-email',
    error: 'Please enter a valid email address',
  },
};

// Disabled state — check contrast and ARIA attributes
export const Disabled: Story = {
  args: {
    label: 'Email address',
    disabled: true,
  },
};

The error state story is particularly important. A common pattern is rendering an error message as a <p> next to an input without associating it via aria-describedby. axe will catch this.

Configuring axe Rules Per Story

Sometimes you need to disable a rule for a specific story — for example, a component that intentionally uses low contrast for decorative text, or a story that demonstrates what a violation looks like for documentation purposes.

export const LowContrastDecorative: Story = {
  args: {
    text: 'Decorative watermark text',
    color: '#cccccc',
  },
  parameters: {
    a11y: {
      config: {
        rules: [
          {
            id: 'color-contrast',
            enabled: false,
          },
        ],
      },
    },
  },
};

You can also configure rules globally in preview.ts:

// .storybook/preview.ts
export const parameters = {
  a11y: {
    config: {
      rules: [
        {
          // Disable this rule globally (not recommended — be specific)
          id: 'autocomplete-valid',
          enabled: false,
        },
      ],
    },
    options: {
      runOnly: {
        type: 'tag',
        values: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'],
      },
    },
  },
};

The runOnly option lets you target specific WCAG levels. If you're aiming for WCAG 2.1 AA compliance, be explicit about it.

Adding Accessibility Assertions in Play Functions

The a11y addon shows violations in the UI, but it doesn't fail your tests automatically by default. To make accessibility violations fail your test run, use checkA11y from axe-playwright inside a play function:

npm install --save-dev axe-playwright
import { checkA11y } from 'axe-playwright';
import type { Meta, StoryObj } from '@storybook/react';
import { within, userEvent } from '@storybook/test';
import { Modal } from './Modal';

const meta: Meta<typeof Modal> = {
  component: Modal,
  title: 'Overlays/Modal',
};

export default meta;
type Story = StoryObj<typeof Modal>;

export const Open: Story = {
  args: {
    isOpen: true,
    title: 'Confirm deletion',
    children: 'Are you sure you want to delete this item?',
  },
  play: async ({ canvasElement }) => {
    // Run axe against the rendered modal
    await checkA11y(canvasElement, {
      runOnly: {
        type: 'tag',
        values: ['wcag2a', 'wcag2aa'],
      },
      // Ignore violations in nested iframes (e.g., from third-party embeds)
      exclude: [['.third-party-iframe']],
    });
  },
};

When checkA11y finds violations, it throws with a detailed error message listing each violation, the affected elements, and a link to the axe documentation explaining the rule and how to fix it.

Combining Interaction and Accessibility Tests

Accessibility doesn't just apply to the initial render. Dynamic components — modals, dropdowns, notifications — need to be accessible after user interaction too. A modal that correctly uses role="dialog" in its initial render but doesn't move focus when opened fails WCAG success criterion 2.4.3 (Focus Order).

Test the accessible state after interactions:

export const OpenedByButton: Story = {
  args: {
    triggerLabel: 'Open settings',
  },
  play: async ({ canvasElement, step }) => {
    const canvas = within(canvasElement);

    await step('Open the modal', async () => {
      await userEvent.click(
        canvas.getByRole('button', { name: 'Open settings' })
      );
    });

    await step('Check modal is accessible when open', async () => {
      // Modal should be in the DOM and have correct role
      const modal = canvas.getByRole('dialog');
      await expect(modal).toBeInTheDocument();
      await expect(modal).toHaveAttribute('aria-labelledby');

      // Focus should move into the modal
      await expect(document.activeElement).toEqual(
        canvas.getByRole('button', { name: 'Close' })
      );

      // Run axe on the open state
      await checkA11y(canvasElement, {
        runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa'] },
      });
    });

    await step('Close the modal and check focus returns', async () => {
      await userEvent.keyboard('{Escape}');

      await expect(
        canvas.getByRole('button', { name: 'Open settings' })
      ).toHaveFocus();
    });
  },
};

This tests the full accessibility lifecycle: keyboard activation, focus management on open, axe compliance in the open state, and focus restoration on close. All of these matter for screen reader and keyboard-only users.

Common Violations and How to Fix Them

Missing Form Labels

// Violation
<input type="email" placeholder="Enter email" />

// Fix: visible label
<label htmlFor="email">Email address</label>
<input id="email" type="email" placeholder="Enter email" />

// Fix: aria-label when visible label isn't possible
<input
  type="email"
  aria-label="Email address"
  placeholder="Enter email"
/>

Insufficient Color Contrast

axe reports the actual and required contrast ratios. For normal text, you need 4.5:1 against its background. Use a contrast checker to find a passing color:

/* Violation: #767676 on white = 4.48:1 (fails by a hair) */
color: #767676;

/* Fix: #757575 is the minimum that passes WCAG AA */
color: #757575;

Missing Button Accessible Names

// Violation: icon-only button with no accessible name
<button onClick={closeModal}>
  <XIcon />
</button>

// Fix: aria-label
<button onClick={closeModal} aria-label="Close modal">
  <XIcon aria-hidden="true" />
</button>

Note aria-hidden="true" on the icon — without it, screen readers might announce the SVG content.

ARIA Live Regions for Dynamic Content

When content updates dynamically (notifications, loading states, search results), screen readers won't announce it unless you use an ARIA live region:

// Violation: dynamic content update with no live region
<div>{statusMessage}</div>

// Fix: announce updates to screen readers
<div role="status" aria-live="polite">{statusMessage}</div>
// or for urgent messages:
<div role="alert" aria-live="assertive">{errorMessage}</div>

Running Accessibility Tests in CI

With the @storybook/test-runner and axe assertions in your play functions, your CI workflow runs accessibility checks as part of the test suite:

name: Accessibility Tests

on: [push, pull_request]

jobs:
  a11y:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npx playwright install chromium --with-deps
      - name: Run Storybook with a11y tests
        run: npx concurrently -k -s first
          "npm run storybook -- --no-open"
          "npx wait-on tcp:6006 && npx test-storybook"

Accessibility violations in play functions will cause the test-runner to exit with a non-zero code, blocking the PR.

For projects that don't yet have play functions, the a11y addon can be configured to fail the test-runner on any violation:

// .storybook/test-runner.ts
import { checkA11y, injectAxe } from 'axe-playwright';

module.exports = {
  async preRender(page) {
    await injectAxe(page);
  },
  async postRender(page) {
    await checkA11y(page, '#storybook-root', {
      detailedReport: true,
      detailedReportOptions: { html: true },
    });
  },
};

This runs axe against every story automatically without adding checkA11y calls to individual play functions. It's the fastest way to get baseline accessibility coverage across an entire component library.

What Automated Accessibility Testing Can't Cover

axe-core finds about 30–40% of accessibility issues automatically. The rest require human judgment:

  • Whether the logical reading order makes sense for screen reader users
  • Whether error messages are clear and actionable
  • Whether the component is usable with a switch device or eye tracking
  • Whether the user journey as a whole is navigable by keyboard

Automated tests are a floor, not a ceiling. They prevent regressions in known rules and catch obvious violations, but they don't replace user testing with people who rely on assistive technology.

For full-application accessibility testing — including the user journey, not just individual components — HelpMeTest can run E2E tests that include keyboard navigation checks and aria attribute assertions across complete workflows, complementing the component-level coverage you get from Storybook's a11y addon.

Summary

@storybook/addon-a11y is the lowest-friction way to add accessibility testing to a React project. Every existing story automatically gets axe-core analysis in the Storybook UI. Adding checkA11y calls in play functions makes violations fail your CI build. The combination catches the most common accessibility violations early, before they get distributed across dozens of pages in your application.

Read more

Start now free