Test A Component That Uses React Portals

August 24, 2020 ยท View on GitHub

When using react-testing-library to render a component that uses Portals, you'll probably run into an issue with your Portal code. When trying to set up the portal, it will fail to find the portal's root element in the DOM.

const portalRoot =
  global.document && global.document.getElementById("portal-root");
// portalRoot is null ๐Ÿ˜ฑ

There are a number of solutions. One solution, recommended by KCD, is to add the portal's root element to the document if it's not already there.

let portalRoot =
  global.document && global.document.getElementById("portal-root");

if (!portalRoot) {
  portalRoot = global.document.createElement("div");
  portalRoot.setAttribute("id", "portal-root");
  global.document.body.appendChild(portalRoot);
}

By solving this issue directly in the portal's source code, you are making it more reliable and don't have to add extra boilerplate to your test setup.

source