Skip to content

Commit

Permalink
Wrap calls to Axe in act() to prevent warnings
Browse files Browse the repository at this point in the history
Axe seems to trigger React state updates, which must be wrapped in act() to prevent warnings.
  • Loading branch information
dpwatrous authored and gingi committed Nov 9, 2023
1 parent 3597d8d commit ae99222
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions packages/bonito-ui/src/test-util/a11y.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ import type { AxeResults, RunOptions } from "axe-core";
import type { JestAxe, JestAxeConfigureOptions } from "jest-axe";
import { MockBrowserEnvironment } from "..";
import { getMockBrowserEnvironment } from "../environment";
import { act } from "react-dom/test-utils";

// Globally configured axe instance
let _axe: JestAxe | null = null;

/**
* A wrapper around react-testing-library's render() function which performs
* accessibility tests after the container is rendered. Note that this is
* an async function unlike render() because running aXe is async.
* an async function unlike render() because running Axe is async.
*
* @param ui The element to render
* @param options Render options
Expand Down Expand Up @@ -66,7 +67,7 @@ export async function runAxe(
// Give a slightly more useful exception if the current environment
// isn't a mock browser env
if (e instanceof Error) {
throw new Error("Unable to run aXe: " + e.message);
throw new Error("Unable to run Axe: " + e.message);
}
throw e;
}
Expand All @@ -82,11 +83,19 @@ export async function runAxe(
} as unknown as AxeResults;
}

if (!_axe) {
throw new Error("aXe was not initialized properly");
let results: AxeResults | null = null;
await act(async () => {
if (!_axe) {
throw new Error("Axe was not initialized properly");
}
results = await _axe(html, options);
});

if (!results) {
throw new Error("Axe did not return results");
}

return _axe(html, options);
return results;
}

/**
Expand Down

0 comments on commit ae99222

Please sign in to comment.