Reactjs 用jest和酶测试定制反应方法

Reactjs 用jest和酶测试定制反应方法,reactjs,jestjs,enzyme,Reactjs,Jestjs,Enzyme,我试图在react组件中测试一个方法。该组件是一个表单,它应该测试在单击submit按钮时调用的handleSubmit()方法。我试过下面的方法 it('handlesSubmit when submit button is clicked', () => { wrapper.find(Button).simulate('click'); expect(wrapper.instance().handleSubmit).toHaveBeenCalled(); })

我试图在react组件中测试一个方法。该组件是一个表单,它应该测试在单击submit按钮时调用的handleSubmit()方法。我试过下面的方法

  it('handlesSubmit when submit button is clicked', () => {
    wrapper.find(Button).simulate('click');
    expect(wrapper.instance().handleSubmit).toHaveBeenCalled();
  })
这给出了一个错误
jest.fn()值必须是模拟函数或间谍。
因此我尝试了以下方法:

it('handlesSubmit when submit button is clicked', () => {
    const handleSubmit = jest.fn();
    wrapper.find(Button).simulate('click');
    expect(handleSubmit).toHaveBeenCalled();
  })

此错误表示
预期已调用模拟函数

第一个块失败,因为wrapper.instance().handleSubmit不是jest模拟函数;它是类方法定义的任何东西

第二个块失败,因为handleSubmit虽然是一个jest模拟函数,但根本没有绑定到包装器组件。它是一个局部变量。当您模拟单击时,它再次调用实际实现

为了完成你想做的事情,你必须这样做

it('handlesSubmit when submit button is clicked', () => {
  const handleSubmit = jest.fn();
  WrapperComponent.prototype.handleSubmit = handleSubmit;
  const wrapper = shallow(<WrapperComponent />);
  wrapper.find(Button).simulate('click');
  expect(handleSubmit).toHaveBeenCalled();
})
it('handlessmit when submit button is click',()=>{
const handleSubmit=jest.fn();
WrapperComponent.prototype.handleSubmit=handleSubmit;
常量包装器=浅();
wrapper.find(Button.simulate('click');
expect(handleSubmit).tohavebeincall();
})
其中WrapperComponent是您正在测试的组件

上述方法应该有效,但有时你可以以更好的方式完成类似的事情。根据组件的实现,通常更容易测试调用handleSubmit方法中的功能,而不是handleSubmit方法本身。例如,如果我的组件是

class TestComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = { clicked: false }
    this.onClick = this.onClick.bind(this)
  }

  onClick() {
   this.props.onClick()
   this.setState({ clicked: true })
  }

  render() {
    return (
      <button onClick={ this.onClick }>
        { 'Click Me' }
      </button>
    )
  }
}
类TestComponent扩展了React.Component{
建造师(道具){
超级(道具)
this.state={clicked:false}
this.onClick=this.onClick.bind(this)
}
onClick(){
this.props.onClick()
this.setState({单击:true})
}
render(){
返回(
{“单击我”}
)
}
}
我可以通过这样做来测试它

it('calls onClick props and sets clicked state to true when clicked', () => {
  const onClick = jest.fn();
  const testComp = shallow(<TestComponent onClick={ onClick } />);
  wrapper.find('button').simulate('click');
  expect(onClick).toHaveBeenCalled();
  expect(testComp.state('clicked')).toBe(true)
})
it('单击时调用onClick props并将单击状态设置为true',()=>{
const onClick=jest.fn();
常量testComp=shallow();
wrapper.find('button').simulate('click');
expect(onClick).tohavebeincall();
expect(testComp.state('clicked')).toBe(true)
})
我通常更喜欢这种类型的测试,因为我不必覆盖原型,而且它实际上是在测试单击是否触发我期望的逻辑。最初的测试只包括我通过了这个.handleSubmit作为onClick道具提交给按钮组件,仅此而已