使用Jest测试React componentWillUnmount

时间:2015-12-06 01:56:16

标签: reactjs jestjs

我正在使用React的TestUtil.renderIntoDocument来测试React组件类like this(只有我使用的是TypeScript而不是Babel):

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

这样可行,但我想编写一个测试来验证componentWillUnmount是否按预期运行。但是,似乎测试运行器从未卸载组件,这并不奇怪。所以我的问题是:如何在测试中卸载组件? TestUtil没有任何看起来像我想要的东西,我会想象removeFromDocument

4 个答案:

答案 0 :(得分:12)

使用enzyme 3库的shallow()unmount(),您可以测试生命周期方法是否像这样调用:

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)
})

答案 1 :(得分:4)

这是正确的,但TestUtils.renderIntoDocument返回一个ReactComponent,可以访问组件的生命周期方法。

因此,您可以手动调用component.componentWillUnmount()

答案 2 :(得分:4)

Step1: Use "jest.spyOn" on "componentWillUnmount" method.
Step2: Trigger unmount on the mounted component.
Finally: check if componentWillUnmount is called when component is unmounted

代码

it('componentWillUnmount should be called on unmount', () => {
    const component = createComponent();
    const componentWillUnmount = jest.spyOn(component.instance(), 'componentWillUnmount');
    component.unmount();
    expect(componentWillUnmount).toHaveBeenCalled();
});

答案 3 :(得分:1)

import { mount } from 'enzyme';
import ReactDOM from 'react-dom';
...

let container;
beforeEach(() => {
   container = document.createElement("div");
   mount(<YourReactComponent />, {attachTo: container});
});

afterEach(() => {
    ReactDOM.unmountComponentAtNode(container);
});