Skip to content

fix: Avoid cleanup error when the container is document - #1473

Open
mkantautas wants to merge 1 commit into
testing-library:mainfrom
mkantautas:fix/cleanup-document-container
Open

mkantautas wants to merge 1 commit into
testing-library:mainfrom
mkantautas:fix/cleanup-document-container

Conversation

@mkantautas

Copy link
Copy Markdown

What:

Fixes #1329: cleanup() throws TypeError: Cannot read properties of null (reading 'removeChild') after rendering or hydrating into container: document with React 18.

Why:

On React 18, unmounting a root rendered into document removes the <html> element, so document.body is null. document.parentNode is also null, so container.parentNode === document.body is true and document.body.removeChild throws. The test fails in the auto-cleanup afterEach even though its assertions passed. React 19 keeps <html>/<body> as singletons, which is why this does not reproduce with the default React 19 setup.

How:

Only remove the container from document.body when document.body exists. Added tests in cleanup.js that render and hydrate into document and then call cleanup(). They fail without the fix in the React 18 jobs (both throw the error above) and pass on React 19 with or without it.

Checklist:

  • Documentation added to the
    docs site N/A
  • Tests
  • TypeScript definitions updated N/A
  • Ready to be merged

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

When container is document, cleanup steps fails with "TypeError: Cannot read properties of null (reading 'removeChild')"

1 participant