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.
Using enzyme 3
library's shallow()
and unmount()
, you can test if lifecycle methods have been called like this:
it(`lifecycle method should have been called`, () => {
const componentDidMount = jest.fn()
const componentWillUnmount = jest.fn()
// 1. First extends your class to mock lifecycle methods
class Foo extends MyComponent {
constructor(props) {
super(props)
this.componentDidMount = componentDidMount
this.componentWillUnmount = componentWillUnmount
}
render() {
return (<MyComponent />)
}
}
// 2. shallow-render and test componentDidMount
const wrapper = shallow(<Foo />)
expect(componentDidMount.mock.calls.length).toBe(1)
expect(componentWillUnmount.mock.calls.length).toBe(0)
// 3. unmount and test componentWillUnmount
wrapper.unmount()
expect(componentDidMount.mock.calls.length).toBe(1)
expect(componentWillUnmount.mock.calls.length).toBe(1)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With