Is there a way to unmount and garbage collect a React Component that was mounted using TestUtils.renderIntoDocument
inside a jsdom test?
I'm trying to test something that happens on componentWillUnmount
and TestUtils.renderIntoDocument
doesn't return any DOM node to call React. unmountComponentAtNode
on.
React has a top-level API called unmountComponentAtNode() that removes a component from a specific container. The function unmountComponentAtNode() takes an argument as a container from which the specific component should be removed.
You can just unmount it conditionally. All you have to do is remove it from the DOM in order to unmount it. As long as renderMyComponent = true , the component will render. If you set renderMyComponent = false , it will unmount from the DOM.
ReactJS – componentWillUnmount() Method This method is called during the unmounting phase of the React Lifecycle, i.e., before the component is destroyed or unmounted from the DOM tree. This method is majorly used to cancel all the subscriptions that were previously created in the componentWillMount method.
No, but you can simply use ReactDOM.render
manually:
var container = document.createElement('div'); ReactDOM.render(<Component />, container); // ... ReactDOM.unmountComponentAtNode(container);
This is exactly what ReactTestUtils does anyway, so there's no reason not to do it this way if you need a reference to the container.
Calling componentWillUnmount
directly won't work for any children that need to clean up things on unmount. And you also don't really need to replicate the renderIntoDocument
method, either since you can just use parentNode
:
React.unmountComponentAtNode(React.findDOMNode(component).parentNode);
Update: as of React 15 you need to use ReactDOM
to achieve the same:
import ReactDOM from 'react-dom'; // ... ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(component).parentNode);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With