I am writing a test for a module that uses react-modal to open a modal. React-modal requires that you set the root element for accessibility reasons.
if (typeof document != "undefined") {
Modal.setAppElement("#root");
}
This however causes an error in tests: "Error: react-modal: No elements were found for selector #root."
I want to mock the function setAppElement in react-modal, but I am obviously missing something because my attempts are not making any difference. If anyone could point out what I'm doing wrong (or any other solution I could do within the test), that would be greatly appreciated.
describe("CustomModal", () => {
vi.mock("react-modal", async () => {
const actual = await vi.importActual("react-modal");
return { ...actual, setAppElement: () => {} };
});
it("Renders successfully", () => {
render(
<CustomModal />
);
});
});
In case someone else has this issue... I solved it by setting the app element like this instead:
<Modal appElement={document.getElementById("root")!}>
And wrapping the render in the test in a div with the id root. It's still setting aria-hidden=true
, and I'm not getting any errors from react-modal.
Mocking it turned out to not be a good solution because react-modal gives an error that the app element has not been set, then.