Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing React componentWillUnmount using Jest

Tags:

reactjs

jestjs

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.

like image 743
Aaron Beall Avatar asked Dec 06 '15 01:12

Aaron Beall


1 Answers

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)
})
like image 133
bob Avatar answered Sep 22 '22 11:09

bob