Skip to content

Commit

Permalink
Filter accessibility violations before unmounting
Browse files Browse the repository at this point in the history
Change a potentially confusing behavior where components were unmounted before
calling the `shouldIgnoreViolation` callback. Querying the rendered tree within
the callback, eg. to get the ID of an element to check if a violation relates to
it, could fail due to this.

Fixes #48.
  • Loading branch information
robertknight committed Oct 22, 2024
1 parent a076a7e commit 2197647
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions src/accessibility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ export type Scenario = {
shouldIgnoreViolation?: (violation: Result) => boolean;
};

async function testScenario(elementOrWrapper: VNode | ReactWrapper) {
async function testScenario(
elementOrWrapper: VNode | ReactWrapper,
{ shouldIgnoreViolation }: Pick<Scenario, 'shouldIgnoreViolation'>,
) {
const container = document.createElement('div');
document.body.appendChild(container);

Expand All @@ -52,10 +55,16 @@ async function testScenario(elementOrWrapper: VNode | ReactWrapper) {
// or "inapplicable" (no relevant HTML elements found).
resultTypes: ['violations'],
});

let violations = results.violations;
if (shouldIgnoreViolation) {
violations = violations.filter(v => !shouldIgnoreViolation(v));
}

wrapper.unmount();
container.remove();

return results.violations;
return violations;
}

function asArray<T>(itemOrList: T | T[]): T[] {
Expand Down Expand Up @@ -95,14 +104,13 @@ export function checkAccessibility(
);
}

const violations = await testScenario(elementOrWrapper);
const filteredViolations = shouldIgnoreViolation
? violations.filter(v => !shouldIgnoreViolation(v))
: violations;
for (const violation of filteredViolations) {
const violations = await testScenario(elementOrWrapper, {
shouldIgnoreViolation,
});
for (const violation of violations) {
console.error('axe-core violation', JSON.stringify(violation, null, 2));
}
if (filteredViolations.length > 0) {
if (violations.length > 0) {
throw new Error(`Scenario "${name}" has accessibility violations`);
}
}
Expand Down

0 comments on commit 2197647

Please sign in to comment.