reactjs - 使用 Jest 测试 React componentWillUnmount

标签 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 的东西。

最佳答案

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

关于reactjs - 使用 Jest 测试 React componentWillUnmount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34113100/

相关文章:

javascript - 如何使用 Framer Motion <AnimatePresence> 和 React Portals?

javascript - 图像上设置的旋转动画在 react native 中不起作用

reactjs - 如何提高测试覆盖率 Jest、Enzyme

reactjs - 如何在 React Context 提供程序中模拟单个值,同时保留其余值

javascript - 如何在 this.state 中使用 this.state

javascript - 将子 Prop 传递给 Gatsby V2 中的子组件

javascript - 使用reactjs,更新列表中的项目而不更新整个列表?

javascript - 模拟整个 es6 类,除了 Jest 中的构造函数?

reactjs - 测试 MobX 组件

javascript - 带有 Jest 的意外 token 导出