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

时间:2017-03-25 21:47:05

标签: reactjs jestjs enzyme

我正在尝试测试反应组件中的方法。该组件是一个表单,应该测试handleSubmit()方法在单击提交按钮时被调用。我试过以下。

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

这给出了错误jest.fn() value must be a mock function or spy.所以我尝试了这个:

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

此错误说Expected mock function to have been called

1 个答案:

答案 0 :(得分:5)

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

第二个块失败,因为handleSubmit虽然是一个jest模拟函数,但根本不依赖于你的包装器组件。这是一个局部变量。当您模拟点击时,它再次调用实际的实现。

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

<head>
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/plugins/tags/bootstrap-tagsinput.css');?>" />

<script type="text/javascript" src="<?php echo base_url('assets/jQuery/jquery-3.1.1.js');?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/plugins/tags/bootstrap-tagsinput.js');?>"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/typeahead.bundle.min.js"></script>
</head>

其中WrapperComponent是您正在测试的组件。

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

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();
})

我可以通过

来测试它
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>
    )
  }
}

我通常更喜欢这种类型的测试,因为我不必覆盖原型,它实际上是测试点击触发了我期望的逻辑。原始测试实际上只涵盖了我传递this.handleSubmit作为onClick道具的Button组件,仅此而已。

相关问题