23

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.

treznik
  • 7,955
  • 13
  • 47
  • 59

5 Answers5

32

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.

Sophie Alpert
  • 139,698
  • 36
  • 220
  • 238
  • 1
    I wrote a little bit about this here with some examples: http://maketea.co.uk/2014/05/22/building-robust-web-apps-with-react-part-3.html#react-test-utilities – i_like_robots Jun 02 '14 at 15:07
  • This is not valid anymore as renderIntoDocument does not touch DOM whatsoever. – pronebird Jul 18 '17 at 11:27
22

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);
Hugues M.
  • 19,846
  • 6
  • 37
  • 65
Chris
  • 758
  • 7
  • 8
  • 1
    As of React 15 you need to use ReactDOM to do this: ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(component).parentNode); – Akhorus Jun 01 '17 at 20:02
8

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);
Sophie Alpert
  • 139,698
  • 36
  • 220
  • 238
carlesba
  • 3,106
  • 3
  • 17
  • 16
0

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

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

afterEach ->
  @myComponent.componentWillUnmount()
Jeff
  • 17
  • 1
  • This is doable if you update props after rendering, but if you need to pass different combinations of props that becomes cumbersome. – pronebird Jul 24 '17 at 16:00
0

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);
MST
  • 649
  • 6
  • 4