【问题标题】:How to use jest.spyOn with react testing library如何将 jest.spyOn 与反应测试库一起使用
【发布时间】:2021-03-13 13:41:35
【问题描述】:

我正在将一个类组件重构为一个功能组件。

在我的测试文件中,我使用了酶,但我正在迁移到 react-testing-library

这是我用酶做的测试

it('should change module when clicked button login', () => {
     const wrapper = mount(<SignUp setModuleCallback={jest.fn()} />)
     const instance = wrapper.instance()

     jest.spyOn(instance, 'setModule')
     wrapper.find('button#login-button').simulate('click')

     expect(instance.setModule).toHaveBeenCalled()
   })

这就是我正在尝试使用 react-testing-library 做的事情

it('should change module when clicked button login', async () => {
     const { getByTestId } = render(<SignUp setModuleCallback={jest.fn()} />)
     const instance = getByTestId('submit')

     jest.spyOn(instance, 'setModule')

     const button = await waitFor(() => getByTestId('submit'))

     act(() => {
       fireEvent.click(button)
     })

     expect(instance.setModule).toHaveBeenCalled()
   })

这是我遇到的错误

【问题讨论】:

  • React 测试库专注于测试 DOM 节点。因此,您的测试将使用实际的 DOM 节点,而不是处理渲染的 React 组件的实例。

标签: reactjs enzyme react-testing-library


【解决方案1】:

RTL 背后的理念是您应该以“使用软件的方式”测试您的组件。考虑到这一点,有没有一种方法可以在不显式断言调用回调的情况下测试您的组件?

根据您的测试名称,您希望某些“模块发生变化”。有什么方法可以在 DOM 中验证模块是否已更改?例如,可能每个“模块”都有一个唯一的标题,在这种情况下,您可以使用screen.getByText 来断言单击按钮后会呈现正确的模块。

如果您想明确断言调用了回调函数,您确定必须使用spyOn 进行此测试吗?我会尝试这样的事情:

it('should change module when clicked button login', async () => {
  const mockCallback = jest.fn()
  const { getByTestId } = render(<SignUp setModuleCallback={mockCallback} />)

  const button = await waitFor(() => getByTestId('submit'))

  act(() => {
    fireEvent.click(button)
  })

  expect(mockCallback).toHaveBeenCalled()
})

【讨论】:

    猜你喜欢
    • 2020-12-19
    • 2019-10-11
    • 2022-01-15
    • 2021-05-09
    • 2022-06-21
    • 1970-01-01
    • 2022-01-02
    • 2021-09-04
    • 2021-10-27
    相关资源
    最近更新 更多