I'm trying to test my Modal
component with React Testing Library. The Modal is rendered inside of a React Portal. Now when I try to match my Modal
with a snapshot the snapshot gets rendered as an empty div.
test('The component should render in body when open', () => {
const {container} = render(
<Modal>
<div>My dialog content</div>
</Modal>
);
expect(container).toMatchSnapshot();
});
The snapshot I get looks like this:
exports[`The component should render in body when open 1`] = `<div />`;
I've seen a few workarounds for instance passing {container: document.body}
as a second argument to the render()
function. But nothing really worked.
Also I cannot query for any elements via container
. It always returns null
.
const dialog = container.querySelector(".modal");
console.log(dialog); // null
I eventually made it work by snapshotting baseElement
instead of container
Both are returned properties by the render()
function.
test('The component should render in body when open', () => {
const {baseElement} = render(
<Modal>
<div>My dialog content</div>
</Modal>
);
expect(baseElement).toMatchSnapshot();
});