How to test enzyme components that render into the top level

4.2k views Asked by At

I'm trying to test a component that renders a grommet Menu component. The grommetMenu component renders an absolutely positioned menu into the top level of the document, inserted as a child to body. Therefore it renders outside the scope of the wrapper. I can find it with document.body.innerHTML (referencing jsdom document) but I want to interact with it using enzyme. Any recommendations?

My Test:

const wrapper = mount(
    <MyComponent checkThis={checkThisSpy} />
);
wrapper.find('.spec-menu').simulate('click');
console.log(document.body.innerHTML); // Shows the absolute menu inserted into the body

The line in grommet that does this document.body.insertBefore(drop.container, document.body.firstChild);. https://github.com/grommet/grommet/blob/master/src/js/utils/Drop.js#L197

Just looking for some guidance on the best way to handle this. Thanks!

1

There are 1 answers

0
Jake Dluhy On BEST ANSWER

Ultimately, we weren't able to find any way to test that the component using enzyme itself. Because we're using jsdom to provide the dom, document is globally available. We ended up writing some expectations that look like

expect(document.getElementsByClassName('my-top-level')).to.have.length(1)

The normal dom API is sufficient to test everything we want, it's just a little clunkier.