react-modal: Modals cannot be tested with React's TestUtil

react-modal is acting outside of the purview of any of React’s test utilities.

renderedModal.getDomNode()
// => <noscript data-reactid=".0"></noscript>

React.scryRenderedDOMComponentsWithClass(renderedModal, "my-modal-class");
// => []

I see there are some work arounds that were developed circa React 0.12 but I can’t figure out why that is necessary. If I was guessing I would say that this has to do with how you mount to the DOM to properly apply the overlay. If this is true, maybe a small wrapper around those helpers as a part of the release would be a helpful thing for us app devs who want to write lots of tests 😃

https://github.com/rackt/react-modal/blob/master/specs/helper.js

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 29 (4 by maintainers)

Most upvoted comments

Bump. We’re currently struggling this as well. Has anyone figured out a reasonable pattern for testing with enzyme?

This blog post has some examples for testing react-modal with enzyme: http://remarkablemark.org/blog/2017/05/17/testing-react-modal/

I know this issue is about React test utils, but is it possible to make testing work with Enzyme.js?

Enzyme.js provides a simpler/cleaner API over React test utils (in my opinion) and it would be handy to be able to utilise that when testing code regarding react-modal.

@jkimbo I figured out my issue. You example worked fine so it was indeed an issue on my side. I was rendering from an external module like

var  renderedModal = TestUtils.renderIntoDocument(
      <MyModule
           props1:{stubblabla}
      />
    );

and calling MyModule.portal, which was obviously wrong, I needed the Modal.portal So for whoever is in trouble like I was: remember to get the Modal component !

TestUtils.findRenderedComponentWithType(component, Modal);

@ramusus I too am unable to get this to work with enzyme 3 and enzyme-adapter-react-15. If you’ve come up with a workaround, please share.

I’ve tried react-dom/test-utils renderIntoDocument then ReactDOM.findDOMNode and scryRenderedDOMComponentsWithClass as recommended here with little to no success.

I’ve also tried the examples from the blog post recommended by @dy-dx with limited success. I’ve been able to get a reference to the portal component but it doesn’t seem to contain any HTML. (Yes, I’ve set isOpen to true.)

I’ve tried using both shallow and mount from enzyme and despite @bethcodes’ experience with shallow, I actually got further with mount. With shallow I had no luck finding any portal.

With enzyme, shallow supports portal components while mount does not. If you absolutely must use mount, you can use ref={(ref) => { this.namedRef = ref; } in order to access the element and then wrap it in an enzyme ReactWrapper.