概要
一部のコンポーネントである特定のルールを無効化したいケースが発生した。無効にする方法については、以下のページにルールの設定方法が載っており、設定することでプレビューではエラーが出なくなった。
https://storybook.js.org/docs/react/writing-tests/accessibility-testing
export const Primary = Template.bind({})
Primary.args = {
children: 'Primary Button',
}
Primary.parameters = {
a11y: {
config: {
rules: [{ id: 'color-contrast', enabled: false }],
},
},
}
ただ、 test-storybookの実行では、無効化したはずのルールがチェックされてしまいエラーになってしまった。上記のページでは特に言及がされておらず、調べていたところ以下のGitHubイシューのコメントが見つかった。
https://github.com/storybookjs/storybook/issues/19896#issuecomment-1320771727
このコメントから辿っていったところ以下のページで、test-runnerのほうで設定を見て処理する必要があることがわかった。
https://github.com/storybookjs/test-runner#utility-functions
対応方法
以下の通り、preRenderで、ストーリの方の設定を見て、チェックをするかしないかなどを制御すれば、設定が反映される。
// .storybook/test-runner.js
const { injectAxe, checkA11y, configureAxe } = require('axe-playwright')
const { getStoryContext } = require('@storybook/test-runner')
module.exports = {
async preRender(page, context) {
await injectAxe(page)
},
async postRender(page, context) {
const storyContext = await getStoryContext(page, context)
if (storyContext.parameters?.a11y?.disable) {
return
}
await configureAxe(page, {
rules: storyContext.parameters?.a11y?.config?.rules,
})
await checkA11y(page, '#root', {
detailedReport: true,
detailedReportOptions: {
html: true,
},
axeOptions: storyContext.parameters?.a11y?.options,
})
},
}