如何通过浅层安装 React Functional 组件对 React Hook 进行单元测试?

How to unit test react hooks by shallow mounting React Functional components?

有没有一种方法可以通过浅安装组件来测试使用 React hooks 构建的功能组件。我发现 Enzyme 不支持 useEffect (https://airbnb.io/enzyme/#react-hooks-support) 和其他浅渲染组件的钩子,我不想进入挂载。

还发现 react-testing-library 是一种新的流行替代方法。与酶相比,它是更好的选择吗?我已经有 Enzyme 用于测试基于 class 的组件。因此,重写这些内容很痛苦。

可以,但需要使用 spies。例如,如果您正在使用 jest,您可以使用 jest.spyOn with mockImplementationOnce(),它也应该与其他 spying 库一起使用。

使用示例:

describe("React useEffect", () => {
  let useEffect, wrapper

  let mockUseEffect = () => {
    useEffect.mockImplementationOnce(f => f())
  }

  beforeEach(() => {
    useEffect = jest.spyOn(React, "useEffect")

    mockUseEffect()
    wrapper = shallow(<SomeComponent />)
  })

  it("your test", () => {
     // using wrapper
  })
}

这是一个很好的详细 [​​=18=] 工作示例。


虽然它有效,但我鼓励您不要使用shallow渲染并开始使用react-testing-library(默认称为@testing-library/react nowadays), Its well-documented, lightweight Testing solution, and I'd say its the the "closest" test you can get to real world scenarios. It comes already with CRA .

这里是来自 React Docs 的基本 codeSandbox example and Here is more examples

此外,这里有一个很棒的 Video by Kent C. Dodds 解决了 shallow 渲染和来自反应测试库的 render 方法之间的差异。