当前位置:  开发笔记 > 编程语言 > 正文

使用Jest测试React componentWillUnmount

如何解决《使用Jest测试ReactcomponentWillUnmount》经验,为你挑选了3个好方法。

我正在使用React TestUtil.renderIntoDocument来测试React组件类,就像这样(只使用TypeScript而不是Babel):

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

这有效,但我想编写一个测试,验证其componentWillUnmount行为符合预期.但是,似乎测试运行器从未卸载组件,这并不奇怪.所以我的问题是:如何在测试中卸载组件?该TestUtil不会有什么看起来像什么,我想,沿着线的东西removeFromDocument我会想象.



1> bob..:

使用enzyme 3shallow()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 ()
    }
  }

  // 2. shallow-render and test componentDidMount
  const wrapper = shallow()

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



2> D P Venkates..:
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> ncuillery..:

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

因此,您可以手动致电component.componentWillUnmount()

推荐阅读
有风吹过best
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有