This is my live code
In my current code I have a div with id #___portal
<div id="___portal"></div>
I have a component where I create a portal adding the content to the #___portal (in my real code, this div will always be created)
import React, { useState, useEffect } from "react";
import { createPortal } from "react-dom";
const App = ({ children }) => {
const [portalEl, setPortalEl] = useState();
useEffect(() => {
//in my real code #___portal exists
setPortalEl(document.getElementById("___portal"));
console.log(portalEl);
}, [portalEl]);
if (!portalEl) return null;
return createPortal(
<>
<div id="modal" role="dialog">
{children}
</div>
</>,
portalEl
);
};
export default App;
I am trying to do a test where I want to test that a text is contained in the component.
My test fails and I suspect that it is because the content of my component is not being added to the #___portal and that is why my component is not rendering, how can I do to simulate this in my test?
import App from "./App";
import React from "react";
import { render } from "react-testing-library";
describe("<App />", () => {
it("Should render text", async () => {
let testId = "___portal";
let newDiv = document.createElement("div");
newDiv.setAttribute("id", testId);
document.body.appendChild(newDiv);
const text = "hello world";
const { getByText } = render(
<App>
<div>{text}</div>
</App>
);
expect(getByText(text)).toBeInTheDocument();
});
});
//output of test
<body>
<div
id="___portal"
/>
<div />
</body>