Aaron Aaron - 16 days ago 10
React JSX Question

Testing React componentWillUnmount using Jest

I am using React's

TestUtil.renderIntoDocument
to test a React component class, like this (only I am using TypeScript instead of Babel):

describe("MyComponent", () => {
it("will test something after being mounted", () => {
var component = TestUtils.renderIntoDocument(<MyComponent />);
// some test...
})
})


This works, but I want to write a test that verifies that
componentWillUnmount
behaves as expected. However, it seems that the test runner never unmounts the component, which is not surprising. So my question is: how do I unmount the component from within a test? The
TestUtil
doesn't have anything that looks like what I want, something along the lines of
removeFromDocument
I would imagine.

Answer

That's right but TestUtils.renderIntoDocument returns a ReactComponent with access to the lifecycle methods of the component.

So you can call manually component.componentWillUnmount().