Sub topic 11
Testing portal content
This chapter covers how to test components that render through createPortal. It assumes you know React function components, useState and useEffect, and the basics of Jest or Vitest with React Testing Library. It also assumes you have read the earlier chapters on createPortal, portal containers, and the modal pattern.
Why portals change how you test
A portal renders its children into a DOM node outside the component's own parent. The component still sits in the same place in the React tree. Tests that assume the two trees match can fail in confusing ways.
When you call render(<Modal />), Testing Library creates a div and appends it to document.body. It returns that div as container. Normal output goes inside container. Portal output goes to wherever the portal targets, often document.body directly, so it is outside container.
This produces a common failure. Code that queries container will not find the portal content. The container queries below return nothing for portal output.
const { container } = render(<Modal onClose={() => {}}>Hello</Modal>);
// Returns null: the dialog is not inside container.
container.querySelector('[role="dialog"]');The fix is to query from document.body. The screen object from Testing Library does this for you.
Querying with screen
screen binds every query to document.body. It finds portal content that targets document.body, and it also finds content in a custom container as long as that container is attached to the body.
Here is the test from the topic plan again, with the Modal from the modal chapter.
import { render, screen } from '@testing-library/react';
import { createPortal } from 'react-dom';
function Modal({ children, onClose }) {
return createPortal(
<div className="backdrop" onClick={onClose}>
<div
className="dialog"
role="dialog"
aria-modal="true"
onClick={(e) => e.stopPropagation()}
>
{children}
</div>
</div>,
document.body
);
}
test('renders modal content outside the container', () => {
const { container } = render(<Modal onClose={() => {}}>Hello</Modal>);
expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(container).not.toContainElement(screen.getByRole('dialog'));
});The two assertions check two different things. The first confirms the dialog exists and is accessible by role. The second confirms the portal did its job and the dialog is not inside the render container. The toBeInTheDocument and toContainElement matchers come from @testing-library/jest-dom. Import it once in your test setup file.
Prefer role queries such as getByRole('dialog') over class names. They test what users and assistive technology see, and they keep working if you rename CSS classes.
Content that is not in the DOM yet
Some portals render only after an effect runs, like the ClientPortal from the server rendering chapter. render wraps your component in act, so effects and the state updates they trigger have already run when it returns. In most cases getBy works. If your component waits on a timer or a promise, use findBy queries, which retry until the element appears or a timeout passes.
const dialog = await screen.findByRole('dialog');Use queryBy when you want to assert absence. getBy throws if nothing matches, so it is the wrong tool for that.
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();Testing a custom portal container
If your component looks up a container by id, the test must create that container first. Otherwise the lookup returns null and the portal renders nothing, which makes tests fail for a reason that has nothing to do with your logic.
This is the ClientPortal from the server rendering chapter, tested with a container created in the test.
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { render, screen } from '@testing-library/react';
function ClientPortal({ children, containerId = 'portal-root' }) {
const [container, setContainer] = useState(null);
useEffect(() => {
setContainer(document.getElementById(containerId));
}, [containerId]);
return container ? createPortal(children, container) : null;
}
describe('ClientPortal', () => {
let root;
beforeEach(() => {
root = document.createElement('div');
root.id = 'portal-root';
document.body.appendChild(root);
});
afterEach(() => {
document.body.removeChild(root);
});
test('renders children into the portal root', () => {
render(<ClientPortal>Inside the root</ClientPortal>);
const text = screen.getByText('Inside the root');
expect(root).toContainElement(text);
});
test('renders nothing when the container is missing', () => {
document.body.removeChild(root);
const { container } = render(<ClientPortal>Lost</ClientPortal>);
expect(screen.queryByText('Lost')).not.toBeInTheDocument();
expect(container).toBeEmptyDOMElement();
// Put the node back so afterEach can remove it.
document.body.appendChild(root);
});
});Note the cleanup. Testing Library unmounts what it rendered after each test, but it does not remove nodes you added by hand. If you skip afterEach, the portal-root nodes pile up across tests, and later tests may find stale content or duplicate ids.
The second test shows the failure case on purpose. A missing container is one of the most common portal bugs, and a test that covers it documents the behavior.
Testing events that cross the portal
The event chapter explained that React events bubble through the React tree, not the DOM tree. You can test that directly. The test below renders a portal button inside a parent with a click handler, then checks that the handler runs.
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { createPortal } from 'react-dom';
function PortalButton() {
return createPortal(<button>Click me</button>, document.body);
}
function Parent({ onParentClick }) {
return (
<div onClick={onParentClick}>
<PortalButton />
</div>
);
}
test('click in a portal reaches the React parent', async () => {
const user = userEvent.setup();
const onParentClick = jest.fn();
render(<Parent onParentClick={onParentClick} />);
await user.click(screen.getByRole('button', { name: 'Click me' }));
expect(onParentClick).toHaveBeenCalledTimes(1);
});The button lives in document.body, so it is not a DOM descendant of the parent div. The handler still fires, because React dispatches the event along the component tree. If you use Vitest, replace jest.fn() with vi.fn().
This kind of test also guards against a real bug. The modal's inner onClick={(e) => e.stopPropagation()} keeps clicks inside the dialog from reaching the backdrop handler. You can test that clicking dialog content does not call onClose, while clicking the backdrop does.
test('closes on backdrop click but not on dialog click', async () => {
const user = userEvent.setup();
const onClose = jest.fn();
render(<Modal onClose={onClose}>Hello</Modal>);
await user.click(screen.getByText('Hello'));
expect(onClose).not.toHaveBeenCalled();
await user.click(screen.getByRole('dialog').parentElement);
expect(onClose).toHaveBeenCalledTimes(1);
});The backdrop has no role or text, so parentElement is a reasonable way to reach it here. If you find yourself doing this often, add a data-testid to the backdrop instead.
Testing the Escape key hook
The useEscapeKey hook adds a listener to document. It lives outside the portal, so the test must dispatch the key event where the listener is. userEvent.keyboard sends events to the focused element, which bubbles up to document, so it works as long as something is focused or the body is active.
import { useEffect } from 'react';
import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
function useEscapeKey(onEscape) {
useEffect(() => {
function handleKeyDown(event) {
if (event.key === 'Escape') onEscape();
}
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [onEscape]);
}
function Probe({ onEscape }) {
useEscapeKey(onEscape);
return null;
}
test('calls onEscape and removes the listener on unmount', async () => {
const user = userEvent.setup();
const onEscape = jest.fn();
const { unmount } = render(<Probe onEscape={onEscape} />);
await user.keyboard('{Escape}');
expect(onEscape).toHaveBeenCalledTimes(1);
unmount();
await user.keyboard('{Escape}');
expect(onEscape).toHaveBeenCalledTimes(1);
});The second half of the test checks cleanup. After unmount, pressing Escape must not call the handler. A listener that survives unmount is the "stray listener" pitfall from the pitfalls chapter, and this assertion catches it.
Testing focus and accessibility
The accessibility chapter covered focus management. Test it by asserting on document.activeElement or with toHaveFocus.
test('moves focus into the dialog and restores it on close', async () => {
const user = userEvent.setup();
function Example() {
const [open, setOpen] = React.useState(false);
return (
<>
<button onClick={() => setOpen(true)}>Open</button>
{open && (
<Modal onClose={() => setOpen(false)}>
<button>Close</button>
</Modal>
)}
</>
);
}
render(<Example />);
const opener = screen.getByRole('button', { name: 'Open' });
await user.click(opener);
expect(screen.getByRole('dialog')).toBeInTheDocument();
});This test only checks that the dialog opens, because the Modal shown so far does not manage focus. Add focus assertions when your modal does, for example expect(screen.getByRole('button', { name: 'Close' })).toHaveFocus() after opening, and expect(opener).toHaveFocus() after closing. A test written first for focus behavior is a good way to drive that feature into the component.
Also check the attributes that assistive technology relies on.
test('dialog has modal semantics', () => {
render(<Modal onClose={() => {}}>Hello</Modal>);
expect(screen.getByRole('dialog')).toHaveAttribute('aria-modal', 'true');
});Edge cases and common test failures
| Symptom | Likely cause | Fix |
|---|---|---|
| `container.querySelector` returns `null` for portal content | Portal output is outside `container` | Query with `screen` or `document.body` |
| `getByRole` finds nothing | The portal container does not exist in the test DOM | Create and attach the container in `beforeEach` |
| Duplicate matches across tests | Hand-made container nodes were never removed | Remove them in `afterEach` |
| Handler fires twice or not at all | Listeners from earlier tests remain on `document` | Unmount in cleanup and check hook cleanup |
| Content is in the DOM but `getByRole` skips it | An ancestor has `aria-hidden` or `hidden` | Pass `{ hidden: true }` or fix the markup |
| Snapshot looks empty | Snapshot taken of `container`, not the body | Snapshot `document.body` or avoid snapshots |
A few details are worth knowing.
jsdomdoes not do layout. A test cannot verify that a portal fixes clipping or stacking, since those depend on real CSS rendering. Use a browser-based test, such as Playwright or Cypress, if that matters. Unit tests should check structure, behavior, and accessibility.jsdomdoes not implement the HTMLinertattribute fully in older versions. If your modal marks the rest of the page as inert oraria-hidden, assert on the attribute, not on whether the browser blocks clicks.- Server rendering behavior needs its own test. Calling
renderToStringfromreact-dom/serveron a component that usesdocumentin render will throw. Testing that a component renders an empty string on the server confirms it is SSR-safe.
import { renderToString } from 'react-dom/server';
test('ClientPortal renders nothing on the server', () => {
const html = renderToString(<ClientPortal>Hidden</ClientPortal>);
expect(html).toBe('');
});This test needs a server-like environment. Under the default jsdom test environment renderToString works, and useEffect does not run during string rendering, so the result is empty either way. That is the same reason the component is safe during hydration.
Summary of practices
- Query with
screen, which searches the wholedocument.body. - Create any portal container the component expects, and remove it after each test.
- Prefer role and accessible-name queries over class names.
- Test event bubbling and
stopPropagationwithuserEvent. - Test cleanup by unmounting and confirming listeners are gone.
- Leave layout and stacking checks to a real browser test.
Exercise
A test renders <Tooltip>Hint</Tooltip>, which uses createPortal to put its content in document.body. The test calls const { container } = render(...) and then expect(container.querySelector('[role="tooltip"]')).toBeInTheDocument(). It fails, although the tooltip appears in the browser. What is wrong, and how do you fix it?
Show answer
The tooltip is rendered into document.body, not into container, so container.querySelector cannot find it. Query from the body instead, for example expect(screen.getByRole('tooltip')).toBeInTheDocument(). You can also assert expect(container).not.toContainElement(screen.getByRole('tooltip')) to confirm the portal moved the content out of the container.
Exercise
Your component uses document.getElementById('modal-root') inside an effect and renders a portal into the result. Its tests pass alone but fail when the whole suite runs, with errors about duplicate elements. What is the likely cause, and what is the fix?
Show answer
A test or setup helper appends a modal-root node to document.body and never removes it, so nodes accumulate across tests. Testing Library only cleans up what it rendered. Create the node in beforeEach and remove it in afterEach, so each test starts with exactly one container.
Exercise
How would you write a test that proves a click inside a portal reaches a handler on the component's React parent, and what does it show about the portal?
Show answer
Render a parent with an onClick mock whose child is a component returning createPortal(<button>Click me</button>, document.body). Click the button found by screen.getByRole('button', { name: 'Click me' }) using userEvent, then assert the mock was called once. The test passes even though the button is not a DOM descendant of the parent, which shows that React events bubble through the React tree.