Sub topic 11
Testing portal content
This chapter assumes you can write component tests with Testing Library and Jest (or Vitest). You should also know the Modal, ClientPortal and useEscapeKey examples from earlier chapters. The tests use @testing-library/jest-dom matchers such as toBeInTheDocument, and @testing-library/user-event for interaction.
Where the portal content ends up
render mounts your component into a div it appends to document.body. That div is the container. A portal moves its children out of that div and into another DOM node, so the container no longer holds them.
Two things follow from this:
- Queries bound to
containerwill not find portal content. - Queries on
screensearchdocument.body, so they do find it.
Query portal content with screen
Here is a Modal that closes on Escape. The test file uses it throughout this chapter.
// Modal.jsx
import { useEffect } from 'react';
import { createPortal } from 'react-dom';
function useEscapeKey(onEscape) {
useEffect(() => {
function handleKeyDown(event) {
if (event.key === 'Escape') onEscape();
}
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [onEscape]);
}
export function Modal({ children, onClose }) {
useEscapeKey(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
);
}The first test checks that the dialog exists and that it sits outside the render container.
// Modal.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Modal } from './Modal';
test('renders modal content outside the container', () => {
const { container } = render(<Modal onClose={() => {}}>Hello</Modal>);
const dialog = screen.getByRole('dialog');
expect(dialog).toBeInTheDocument();
expect(container).not.toContainElement(dialog);
expect(document.body).toContainElement(dialog);
});Asserting that the container does not hold the dialog confirms the portal is working. If the component accidentally rendered inline, this assertion would fail.
Test behavior, not just placement
Interaction tests work the same way as for any other component. Events dispatched on portal nodes bubble through the React tree, so your handlers fire as they would in the browser.
test('closes on Escape', async () => {
const onClose = jest.fn();
render(<Modal onClose={onClose}>Hello</Modal>);
await userEvent.keyboard('{Escape}');
expect(onClose).toHaveBeenCalledTimes(1);
});
test('clicking inside the dialog does not close it', async () => {
const onClose = jest.fn();
render(<Modal onClose={onClose}>Hello</Modal>);
await userEvent.click(screen.getByText('Hello'));
expect(onClose).not.toHaveBeenCalled();
});In Vitest, replace jest.fn() with vi.fn().
You can also test the bubbling behavior from the earlier chapter directly. Pass the parent handler as a prop so the test can observe it:
import { createPortal } from 'react-dom';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
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 onParentClick = jest.fn();
render(<Parent onParentClick={onParentClick} />);
await userEvent.click(screen.getByRole('button', { name: 'Click me' }));
expect(onParentClick).toHaveBeenCalledTimes(1);
});Provide the container your component expects
A component such as ClientPortal looks up a node by id. The test environment has no #portal-root unless you create one. Add it before each test and remove it afterward so tests stay independent.
import { render, screen, within } from '@testing-library/react';
import { ClientPortal } from './ClientPortal';
beforeEach(() => {
const root = document.createElement('div');
root.id = 'portal-root';
document.body.appendChild(root);
});
afterEach(() => {
document.getElementById('portal-root')?.remove();
});
test('renders into #portal-root', () => {
render(<ClientPortal>Tooltip text</ClientPortal>);
const root = document.getElementById('portal-root');
expect(within(root).getByText('Tooltip text')).toBeInTheDocument();
});render wraps updates in act, so the effect that finds the container has already run when render returns. The synchronous query works. within(root) limits the query to one node, which is useful when several portals are open at once.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Unable to find an element` when using `container.querySelector` | Portal content is not inside the container | Query with `screen`, or use `baseElement` |
| `ClientPortal` renders nothing | `#portal-root` does not exist in the test DOM | Create it in `beforeEach` |
| A second test finds elements from the first | A manually added node was never removed | Remove it in `afterEach` |
| Escape test calls the handler twice | A listener from an earlier render is still attached | Check the effect cleanup in the hook |
Testing Library unmounts rendered trees after each test automatically, which also removes portal content created by createPortal. Nodes you added yourself are not cleaned up, which is why the afterEach above matters.
Exercise
A test renders <Modal onClose={fn}>Hello</Modal> and calls container.querySelector('[role="dialog"]'). It returns null, yet the modal works in the browser. Why does this happen, and how do you fix the query?
Show answer
Modal uses createPortal(..., document.body), so the dialog is a child of document.body, not of the render container. Querying the container cannot find it. Use screen.getByRole('dialog'), which searches document.body, or use baseElement from render.