Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to test a component rendered using React.createportal?

I am using jest and react testing library. While i am trying to render the component i am not able to test it. Can you guys tell me the correct method to do it.

it("Render PopUp Properly", () => {
      const props = {
        setIsOpen: jest.fn(),
        children: <div>Test</div>,
      };
      const {getByTestId}= render(<Popup isOpen={true} {...props} />);
      expect(screen.getByTestId("popup-component")).toBeInTheDocument();
    });

Got the following error:

PopUp › Render PopUp Properly                            
                                                             
    Target container is not a DOM element.

      13 |   }
      14 |
    > 15 |   return createPortal(
         |                      ^
      16 |     <motion.div
      17 |       data-testid="blur-bg"
      18 |       initial={{

I was expecting my component to render properly but got that error instead.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  it("Render PopUp Properly", () => {
      const props = {
        setIsOpen: jest.fn(),
        children: <div>Test</div>,
      };
      const container = document.createElement("div");
      document.body.appendChild(container);
      ReactDOM.createPortal(<Popup isOpen={true} {...props} />, container);
      expect(container.innerHTML).toMatchSnapshot();
      expect(container).toBeInTheDocument();
    });

this works for me.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading