69 lines
2.3 KiB
TypeScript
69 lines
2.3 KiB
TypeScript
/**
|
|
* `generateA11yTest` is the canonical test-template documented in the WCAG
|
|
* internal-coverage spec
|
|
* (`docs/improvement-plan/10-compliance-polish/wcag-internal.md`, section a).
|
|
*
|
|
* Components in `packages/ui-app` and `packages/ui-subframe` should ship a
|
|
* co-located `<ComponentName>.a11y.test.tsx` that simply calls this helper
|
|
* with sensible default props. Complex components (Modal, Combobox,
|
|
* DataTable, …) keep additional manually-authored tests for focus-trap and
|
|
* keyboard-navigation behaviour.
|
|
*
|
|
* The helper intentionally lives in the public test-utils tree so that
|
|
* consumer packages such as apps/web can re-use the same template
|
|
* without copying boilerplate.
|
|
*/
|
|
import type { ComponentType, ComponentProps, ReactNode } from "react";
|
|
import { describe, it } from "vitest";
|
|
import { createElement } from "react";
|
|
|
|
import { expectNoAxeViolations } from "../../test-setup/axe.js";
|
|
|
|
export interface GenerateA11yTestOptions {
|
|
/**
|
|
* Human-readable name shown in test output. Defaults to
|
|
* `<Component.displayName>` or `<Component.name>`.
|
|
*/
|
|
readonly name?: string;
|
|
/**
|
|
* Optional axe-rule overrides (see {@link AxeRunOptions} in
|
|
* `test-setup/axe.ts`). Use to relax rules for components that
|
|
* intentionally violate them in isolation (rare).
|
|
*/
|
|
readonly axe?: Parameters<typeof expectNoAxeViolations>[1];
|
|
}
|
|
|
|
function displayName<P>(Component: ComponentType<P>): string {
|
|
return (Component as { displayName?: string }).displayName
|
|
?? (Component as { name?: string }).name
|
|
?? "Component";
|
|
}
|
|
|
|
/**
|
|
* Emit a `describe(... a11y) { it("has no axe violations") }` block for the
|
|
* given component + default props.
|
|
*
|
|
* @example
|
|
* ```tsx
|
|
* import { Button } from "./Button";
|
|
* import { generateA11yTest } from "../test-utils/a11y-template";
|
|
*
|
|
* generateA11yTest(Button, { children: "Click me" });
|
|
* ```
|
|
*/
|
|
export function generateA11yTest<T extends ComponentType<any>>(
|
|
Component: T,
|
|
defaultProps: Partial<ComponentProps<T>> & { children?: ReactNode },
|
|
options: GenerateA11yTestOptions = {},
|
|
): void {
|
|
const label = options.name ?? displayName(Component);
|
|
describe(`${label} a11y`, () => {
|
|
it("has no axe violations with default props", async () => {
|
|
await expectNoAxeViolations(
|
|
createElement(Component as ComponentType<any>, defaultProps as any),
|
|
options.axe,
|
|
);
|
|
});
|
|
});
|
|
}
|