react-modal: setAppElement throws error in tests

Summary:

When running in test, the lib/helpers/ariaAppHider.js:24 throws:

Error: react-modal: No elements were found for selector #app.

Expected behavior:

Should not throw errors in test.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 27
  • Comments: 20

Commits related to this issue

Most upvoted comments

In order to fix this issue, I did the following in all my components that use react-modal:

if (process.env.NODE_ENV !== 'test') ReactModal.setAppElement('#app');

Guys, you can just simply set a mock function for this and get out of this. taddaaaa Just write it before your describe and here you go…

jest
  .spyOn(Modal, "setAppElement")
  .mockImplementation(param => console.log(`setAppElement:'${param}'`));
describe("<Component />", () => {

}

Happy coding!!

I too am having the same issue, #668 didn’t fix this for me.

Great. That’s one way.

Another way would be to move the setAppElement() to a file that doesn’t go into the tests.

In case your tests really need to set the element, here is an example (but this will depend on the test environment):

ReactModal.setAppElement(document.createElement('div'));
describe("test component that uses modal", () => {
   ...
});

was able to work around the error by setting appElement directly on the modal.

<Modal appElement={document.querySelector('#app')}>

I got similar error . i am using jest so i decided to follow below solution

Solution: setup global mock for React Modal and override setAppElement method

//__mocks__/react-modal.js
const Modal = require('react-modal')

const oldFn = Modal.setAppElement
Modal.setAppElement = element => {
  if (element === '#___gatsby') {
   // otherwise it will throw aria warnings.
   return oldFn(document.createElement('div'))
  }
  oldFn(element)
}
module.exports = Modal

Will this problem ever be fully addressed?

I just ended up dropping this on the modal:

ariaHideApp={ !process.env.NODE_ENV === 'test' }

I got rid of the error in a dumb way.

import * as Modal from 'react-modal';

it('renders without crashing', () => {
    Modal.setAppElement = () => null;
    ReactDOM.render(<Foo />, div);
});

I had the same issue,

Work around of it like this

if (this.props.modalApp) {
            Modal.setAppElement(this.props.modalApp);  //'#app'
}

With same principal. Thanks…