'react testing library: how to test component in which user press button after should open modal in react portal

I am testing this component Sidebar

const Sidebar = () => {
  const { modalVisible, modalVisibleHandler } = useModalVisible();
 
  return (
    <div className="sidebar">
      <Profile />
      <Menu />
      <WorkSpace all={true} />
      <SidebarButton openModal={modalVisibleHandler} />
     
      {modalVisible && (
        <Portal>
          <TaskCreate />
        </Portal>
      )}
    </div>
  );
};

My Portal component

import { useEffect } from "react";
import ReactDOM from "react-dom";
const modalRoot = document.getElementById("modal-root");

export default function Portal({ children }: { children: any }) {
  const el = document.createElement("div");
  useEffect(() => {
    if (modalRoot) {
      modalRoot.appendChild(el);
    }
    return () => {
      if (modalRoot) modalRoot.removeChild(el);
    };
  }, [el]);
  return ReactDOM.createPortal(children, el);
}

and TaskCreate component

const TaskCreate = () => (
    <div
      className="task-create task-view"
      id="task-create"
    >
      this component will open when user click button in Sidebar component 
    </div>
  );

I have in TaskCreate component id="task-create" so before user click on "open modal" in Sidebar, TaskCreate component with id "task-create" I need to test that this id not.toBeInTheDocument() and after user click toBeInTheDocument()

The problem is that Portal is connect with id "modal-root" which is in the index.html and my test can't get this bind



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source