Automatically run Jest accessibility tests on Storybook stories.
This package is hosted through GitHub Package Registry (GPR). Currently, GPR requires an access token even if the package is publicly available. Be sure you've properly configured npm or Yarn with your personal access token before installing this package.
Once your environment is properly configured, install the package with the following command:
npm i -D @imaginelearning/test-storybook-a11y
# or
yarn add -D @imaginelearning/test-storybook-a11y
It also requires the following peer dependencies:
This package exports a single default function. Import the function into a test file, then call it with a glob pattern for matching your Storybook story files. It will automatically render each story from all matching story files, and test the rendered output with the axe-core accessibility engine for accessibility violations.
// src/a11y.test.ts
import testStorybookA11y from '@imaginelearning/test-storybook-a11y';
testStorybookA11y('./**/*.stories.@(jsx|tsx)');
If your Storybook uses global decorators, you can provide a second parameter which a GlobalStoryConfig
object:
interface GlobalStoryConfig {
decorators: StoryDecorator[];
globals: Args;
}
The decorators
property would typically be set with the decorators exported from your preview.js
file.
// src/a11y.test.ts
import testStorybookA11y from '@imaginelearning/test-storybook-a11y';
import { decorators } from '../.storybook/preview';
testStorybookA11y('./**/*.stories.@(jsx|tsx)', { decorators });
If your decorators make use of globalTypes
those values can be included as well.
// src/a11y.test.ts
import testStorybookA11y from '@imaginelearning/test-storybook-a11y';
import { decorators } from '../.storybook/preview';
testStorybookA11y('./**/*.stories.@(jsx|tsx)', {
decorators,
globals: { language: 'en' },
});
For more control over the test execution itself, you can provide an optional third parameter, which is a TestOptions
object:
interface TestOptions {
timeout?: number;
axeOptions?: axe.RunOptions;
}
The timeout
property determines how long the test will wait for rendering to settle,
using DOM Testing Library's waitFor
function.
The default value is 1000 milliseconds.
The axeOptions
property is options
parameter passed directly to axe-core
.
// src/a11y.test.ts
import testStorybookA11y from '@imaginelearning/test-storybook-a11y';
testStorybookA11y('./**/*.stories.@(jsx|tsx)', undefined, {
timeout: 5000,
axeOptions: {
runOnly: ['wcag2a', 'wcag2aa'],
},
});
Using this package does not ensure comprehensive accessibility testing in your project. It is a quick and simple way to add some level of automated accessibility testing by leveraging your existing Storybook stories. Keep in mind that by default Jest uses jsdom to render your components, so while it can help to identify structural issues, unless you're rendering styles in your unit tests it's not likely to identify style issues--such as improper color contrast.