4
votes

I would like to test a component built with react-modal. The library uses portals to mount the actual modal outside the parent. The find method in enzyme only looks though the tree starting at your wrapper element, which does not include the open modal.

From what I can tell, until recently, portals were not officially supported, but as of React 16 and Enzyme 3, they should be (enzyme-252)

It looks like the open portal is accessible in the DOM from an enzyme-mounted component, but it is not easy to find it. I have seen strategies using refs (which I would rather not add just for testing), and document.querySelector (worse than dealing with a ReactWrapper).

The most promising strategy claimed the portal was accessible from it's parent using foundEl.node.portal (react-modal-563, but I have not gotten this to work (it appears that perhaps the node property has been deprecated, because when I use it, I get an error: Attempted to access ReactWrapper::node, which was previously a private property on Enzyme ReactWrapper instances, but is no longer and should not be relied upon. Consider using the getElement() method instead.

Has anyone found a better strategy or gotten this one to work? I am on Enzyme 3.1.1, React Enzyme Adaptor 1.0.4, and React 16.2 for reference.

const wrapper = mount(
      <div>
          <Provider store={store}>
              <MyModal isOpen={true} />
          </Provider>
      </div>
);
console.log('modal node', wrapper.find(ReactModal).node) // error
console.log('modal element', wrapper.find(ReactModal).getElement(0)) // ReactModal element with props, etc, but no portal
console.log('from query', document.querySelector(`.ReactModalPortal`)) // Finds it, but I would rather not do it this way
1
Is there a reason you can't extract the contents of the portal into a new component, and test that instead? There is probably no need for you to test the actual portal functionality.Conor Strejcek
I am unit testing the contents. I wanted to write some integration tests, since there is a fair amount of logic in the redux-connection layer (The modal is composed into a connected component). It would be doable to test a lot of those mappers and selectors in isolation as well, but was hoping to do enough of an integration test for some of the core functionality to take pressure off end to end tests.Cgalbiati
the 2nd task on github.com/airbnb/enzyme/issues/1553 would seem to indicate that enzyme doesn't yet support this.Andrew Farrell

1 Answers

0
votes

ReactDOM.createPortal = jest.fn(modal => modal)