功能组件中的笑话/酶模拟功能

use*_*079 13 mocking reactjs jestjs enzyme

我有一个功能组件,我想用模拟功能测试它(简化演示)

const remove = () => {
  ... do something
}

const removeButton = (props) => (
  <Button onClick={() => remove()}>
    Remove
  </Button>
);
Run Code Online (Sandbox Code Playgroud)

我试过这个测试用例

it('test remove button', () => {
  const test = shallow(<removeButton/>)
  const mockFunction = jest.fn()
  test.instance().remove = mockFunction
  test.find('Button').simulate('click')
  expect(mockFunction).toHaveBeenCalled()
})
Run Code Online (Sandbox Code Playgroud)

.instance().remove 无法模拟该函数,因为它超出了范围。我将如何模拟 remove 函数?

djf*_*dev 0

您应该将remove函数作为 prop 传递,而不是仅仅定义模块私有的相邻变量。

const removeButton = (props) => (
  <Button onClick={() => props.remove()}>
    Remove
  </Button>
)

// test file
it('test remove button', () => {
  const mockFunction = jest.fn()
  const test = shallow(<RemoveButton remove={mockFunction} />)
  test.find('Button').simulate('click')
  expect(mockFunction).toHaveBeenCalled()
})
Run Code Online (Sandbox Code Playgroud)

  • 是否可以模拟私有函数?因为这种情况在我的项目中经常发生 (4认同)