问题
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.
回答1:
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.
回答2:
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);
回答3:
Just to update @BenAlpert 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);
回答4:
After your test you can call componentWillUnmount() on the component manually.
beforeEach ->
@myComponent = React.addons.TestUtils.renderIntoDocument <MyComponent/>
afterEach ->
@myComponent.componentWillUnmount()
回答5:
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);
来源:https://stackoverflow.com/questions/23973942/unmount-destroy-component-in-jsdom-test