Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Addon A11y: Introduce parameters.a11y.test #30516

Merged
merged 6 commits into from
Feb 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions code/addons/a11y/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,3 @@ export const DOCUMENTATION_DISCREPANCY_LINK = `${DOCUMENTATION_LINK}#why-are-my-
export const TEST_PROVIDER_ID = 'storybook/addon-a11y/test-provider';

export const EVENTS = { RESULT, REQUEST, RUNNING, ERROR, MANUAL };

export const A11Y_TEST_TAG = 'a11y-test';
3 changes: 3 additions & 0 deletions code/addons/a11y/src/params.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { ElementContext, RunOptions, Spec } from 'axe-core';

type A11yTest = 'off' | 'todo' | 'error';

export interface Setup {
element?: ElementContext;
config: Spec;
Expand All @@ -13,4 +15,5 @@ export interface A11yParameters {
/** @deprecated Use globals.a11y.manual instead */
manual?: boolean;
disable?: boolean;
test?: A11yTest;
}
39 changes: 24 additions & 15 deletions code/addons/a11y/src/preview.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { StoryContext } from 'storybook/internal/csf';

import { run } from './a11yRunner';
import { A11Y_TEST_TAG } from './constants';
import { experimental_afterEach } from './preview';
import { getIsVitestRunning, getIsVitestStandaloneRun } from './utils';

Expand Down Expand Up @@ -88,12 +87,13 @@ describe('afterEach', () => {
addReport: vi.fn(),
},
parameters: {
a11y: {},
a11y: {
test: 'error',
},
},
globals: {
a11y: {},
},
tags: [A11Y_TEST_TAG],
...overrides,
}) as any;

Expand Down Expand Up @@ -138,33 +138,39 @@ describe('afterEach', () => {
});
});

it('should report passed status when there are no violations', async () => {
const context = createContext();
it('should run accessibility checks and should report them as warnings', async () => {
const context = createContext({
parameters: {
a11y: {
test: 'todo',
},
},
});
const result = {
violations: [],
violations,
};

mockedRun.mockResolvedValue(result as any);
mocks.getIsVitestStandaloneRun.mockReturnValue(false);

await experimental_afterEach(context);

expect(mockedRun).toHaveBeenCalledWith(context.parameters.a11y);

expect(context.reporting.addReport).toHaveBeenCalledWith({
type: 'a11y',
version: 1,
result,
status: 'passed',
status: 'warning',
});
});

it('should run accessibility checks if "a11y-test" flag is not available and is not running in Vitest', async () => {
const context = createContext({
tags: [],
});
it('should report passed status when there are no violations', async () => {
const context = createContext();
const result = {
violations: [],
};
mockedRun.mockResolvedValue(result as any);
vi.mocked(getIsVitestRunning).mockReturnValue(false);

await experimental_afterEach(context);

Expand Down Expand Up @@ -222,11 +228,14 @@ describe('afterEach', () => {
expect(context.reporting.addReport).not.toHaveBeenCalled();
});

it('should not run accessibility checks if vitest is running and story is not tagged with a11ytest', async () => {
it('should not run accessibility checks when parameters.a11y.test is "off"', async () => {
const context = createContext({
tags: [],
parameters: {
a11y: {
test: 'off',
},
},
});
vi.mocked(getIsVitestRunning).mockReturnValue(true);

await experimental_afterEach(context);

Expand Down
28 changes: 20 additions & 8 deletions code/addons/a11y/src/preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ import type { AfterEach } from 'storybook/internal/types';
import { expect } from '@storybook/test';

import { run } from './a11yRunner';
import { A11Y_TEST_TAG } from './constants';
import type { A11yParameters } from './params';
import { getIsVitestRunning, getIsVitestStandaloneRun } from './utils';
import { getIsVitestStandaloneRun } from './utils';

let vitestMatchersExtended = false;

Expand All @@ -14,20 +13,27 @@ export const experimental_afterEach: AfterEach<any> = async ({
reporting,
parameters,
globals,
tags,
}) => {
const a11yParameter: A11yParameters | undefined = parameters.a11y;
const a11yGlobals = globals.a11y;

const shouldRunEnvironmentIndependent =
a11yParameter?.manual !== true &&
a11yParameter?.disable !== true &&
a11yParameter?.test !== 'off' &&
a11yGlobals?.manual !== true;

if (shouldRunEnvironmentIndependent) {
if (getIsVitestRunning() && !tags.includes(A11Y_TEST_TAG)) {
return;
const getMode = (): (typeof reporting)['reports'][0]['status'] => {
switch (a11yParameter?.test) {
case 'todo':
return 'warning';
case 'error':
default:
return 'failed';
}
};

if (shouldRunEnvironmentIndependent) {
try {
const result = await run(a11yParameter);

Expand All @@ -38,7 +44,7 @@ export const experimental_afterEach: AfterEach<any> = async ({
type: 'a11y',
version: 1,
result: result,
status: hasViolations ? 'failed' : 'passed',
status: hasViolations ? getMode() : 'passed',
});

/**
Expand All @@ -50,7 +56,7 @@ export const experimental_afterEach: AfterEach<any> = async ({
* implement proper try catch handling.
*/
if (getIsVitestStandaloneRun()) {
if (hasViolations) {
if (hasViolations && getMode() === 'failed') {
if (!vitestMatchersExtended) {
const { toHaveNoViolations } = await import('vitest-axe/matchers');
expect.extend({ toHaveNoViolations });
Expand Down Expand Up @@ -88,3 +94,9 @@ export const initialGlobals = {
manual: false,
},
};

export const parameters = {
a11y: {
test: 'todo',
} as A11yParameters,
};
9 changes: 0 additions & 9 deletions code/addons/test/src/vitest-plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,15 +224,6 @@ export const storybookTest = async (options?: UserOptions): Promise<Plugin[]> =>
},
};
},
getTags: () => {
const envConfig = JSON.parse(process.env.VITEST_STORYBOOK_CONFIG ?? '{}');

const shouldSetTag = process.env.VITEST_STORYBOOK
? (envConfig.a11y ?? false)
: false;

return shouldSetTag ? ['a11y-test'] : [];
},
},
// if there is a test.browser config AND test.browser.screenshotFailures is not explicitly set, we set it to false
...(inputConfig_ONLY_MUTATE_WHEN_STRICTLY_NEEDED_OR_YOU_WILL_BE_FIRED.test?.browser &&
Expand Down
5 changes: 2 additions & 3 deletions code/addons/test/src/vitest-plugin/test-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,10 @@ import { setViewport } from './viewports';
declare module '@vitest/browser/context' {
interface BrowserCommands {
getInitialGlobals: () => Promise<Record<string, any>>;
getTags: () => Promise<string[] | undefined>;
}
}

const { getInitialGlobals, getTags } = server.commands;
const { getInitialGlobals } = server.commands;

export const testStory = (
exportName: string,
Expand All @@ -34,7 +33,7 @@ export const testStory = (
const composedStory = composeStory(
annotations.story,
annotations.meta!,
{ initialGlobals: (await getInitialGlobals?.()) ?? {}, tags: await getTags?.() },
{ initialGlobals: (await getInitialGlobals?.()) ?? {} },
annotations.preview,
exportName
);
Expand Down
14 changes: 4 additions & 10 deletions code/core/template/stories/tags-add.stories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,11 @@ export default {

export const Inheritance = {
tags: ['story-one', '!vitest'],
play: async ({ canvasElement, tags }: PlayFunctionContext<any>) => {
play: async ({ canvasElement }: PlayFunctionContext<any>) => {
const canvas = within(canvasElement);
if (tags.includes('a11y-test')) {
await expect(JSON.parse(canvas.getByTestId('pre').innerText)).toEqual({
tags: ['a11y-test', 'story-one'],
});
} else {
await expect(JSON.parse(canvas.getByTestId('pre').innerText)).toEqual({
tags: ['story-one'],
});
}
await expect(JSON.parse(canvas.getByTestId('pre').innerText)).toEqual({
tags: ['story-one'],
});
},
parameters: { chromatic: { disable: false } },
};
Expand Down
22 changes: 4 additions & 18 deletions code/core/template/stories/tags-config.stories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,11 @@ export default {

export const Inheritance = {
tags: ['story-one', '!vitest'],
play: async ({ canvasElement, tags }: PlayFunctionContext<any>) => {
play: async ({ canvasElement }: PlayFunctionContext<any>) => {
const canvas = within(canvasElement);
if (tags.includes('a11y-test')) {
await expect(JSON.parse(canvas.getByTestId('pre').innerText)).toEqual({
tags: [
'dev',
'test',
'a11y-test',
'component-one',
'component-two',
'autodocs',
'story-one',
],
});
} else {
await expect(JSON.parse(canvas.getByTestId('pre').innerText)).toEqual({
tags: ['dev', 'test', 'component-one', 'component-two', 'autodocs', 'story-one'],
});
}
await expect(JSON.parse(canvas.getByTestId('pre').innerText)).toEqual({
tags: ['dev', 'test', 'component-one', 'component-two', 'autodocs', 'story-one'],
});
},
parameters: { chromatic: { disable: false } },
};
Expand Down
14 changes: 4 additions & 10 deletions code/core/template/stories/tags-remove.stories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,11 @@ export default {

export const Inheritance = {
tags: ['story-one', '!vitest'],
play: async ({ canvasElement, tags }: PlayFunctionContext<any>) => {
play: async ({ canvasElement }: PlayFunctionContext<any>) => {
const canvas = within(canvasElement);
if (tags.includes('a11y-test')) {
await expect(JSON.parse(canvas.getByTestId('pre').innerText)).toEqual({
tags: ['dev', 'test', 'a11y-test', 'component-one', 'autodocs', 'story-one'],
});
} else {
await expect(JSON.parse(canvas.getByTestId('pre').innerText)).toEqual({
tags: ['dev', 'test', 'component-one', 'autodocs', 'story-one'],
});
}
await expect(JSON.parse(canvas.getByTestId('pre').innerText)).toEqual({
tags: ['dev', 'test', 'component-one', 'autodocs', 'story-one'],
});
},
parameters: { chromatic: { disable: false } },
};
Expand Down
Loading