Unmount / destroy Component in jsdom test

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.

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);

Just to update @SophieAlpert answer. React.renderComponent will be deprecated soon so you should use ReactDOM methods instead:

var container = document.createElement('div');
ReactDOM.render(<Component />, container);
// ...
ReactDOM.unmountComponentAtNode(container);

After your test you can call componentWillUnmount() on the component manually.

beforeEach ->
  @myComponent = React.addons.TestUtils.renderIntoDocument <MyComponent/>

afterEach ->
  @myComponent.componentWillUnmount()

Just stumbled across this question, figure I would provide a way to directly tackle it using the described renderIntoDocument API. This solution works in the context of PhantomJS.

To mount onto the document node:

theComponent = TestUtils.renderIntoDocument(<MyComponent/>);

To unmount from the document node:

React.unmountComponentAtNode(document);


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Run two commands at the same time in Elm

Similar Posts