Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unmount / destroy Component in jsdom test

Tags:

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.

like image 483
treznik Avatar asked May 31 '14 19:05

treznik


People also ask

How do you destroy components in react?

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.

How do I unmount a component from a DOM?

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.

What is unmount component?

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.


2 Answers

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.

like image 78
Sophie Alpert Avatar answered Sep 30 '22 01:09

Sophie Alpert


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); 
like image 41
Chris Avatar answered Sep 30 '22 02:09

Chris