Skip to content

cleanupAtContainer should call ReactDOM.unmountComponentAtNode before removing the container from the DOM #326

Closed
@MarkFalconbridge

Description

@MarkFalconbridge
  • react-testing-library version: 6.0.0
  • react version: 16.8.1
  • node version:
  • npm (or yarn) version:

Relevant code or config

function cleanupAtContainer(container) {
  if (container.parentNode === document.body) {
    document.body.removeChild(container)
  }
  ReactDOM.unmountComponentAtNode(container)
  mountedContainers.delete(container)
}

What you did:
Using react-testing-library my unmount code is not getting run until after the container has been removed from the DOM which in itself results in React emitting events to my component.

My component under test listens to onBlur events, when received it uses setTimeout to subsequently determine whether focus is still within that element or not and then possibly updates some internal state depending on whether it still contains focus or not. To make sure that the component doesn't try to update that state after being unmounted the handle from setTimeout is stored and clearTimeout called with it when the component will be unmounted.

What happened:

When cleanupAtContainer calls document.body.removeChild(container) my component under test receives a blur event so then uses setTimeout, then the callback for setTimeout runs and my component tries to set some internal state but React determines that my component isn't in the DOM any more so throws an exception seen in in the browser console.

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

Reproduction repository:
https://github.com/alexkrolick/dom-testing-library-template

Problem description:

Suggested solution:

I believe the order of

if (container.parentNode === document.body) {
    document.body.removeChild(container)
  }

and

ReactDOM.unmountComponentAtNode(container)

should be swapped.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions