Search code examples
reactjsnext.jsjestjsreact-testing-library

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.


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.