在测试环境中触发this.props.dispatch

时间:2017-05-12 19:42:51

标签: javascript reactjs jestjs enzyme

你好,我有一个像这样的Jest / Enzyme测试:

it('triggers checkbox onChange event', () => {
  const configs = {
    default: true,
    label: 'My Label',
    element: 'myElement',
  }
  const checkbox = shallow(
    <CheckBox
      configs={configs}
    />
  )
  checkbox.find('input').simulate('click')
})

一个看起来像这样的组件:

<div className="toggle-btn sm">
  <input 
    id={this.props.configs.element} 
    className="toggle-input round" 
    type="checkbox" 
    defaultChecked={ this.props.defaultChecked } 
    onClick={ e => this.onChange(e.target) }
  >
  </input>
</div>

单击input会调用此方法:

this.props.dispatch(update(data))

它在我的浏览器中运行正常,但是在测试onClick事件时我收到此错误:

TypeError: this.props.dispatch is not a function

如何让this.props.dispatch在我的考试中工作?

由于

1 个答案:

答案 0 :(得分:1)

您需要在测试中将dispatch作为道具传递。

以下修改后的代码:

it('triggers checkbox onChange event', () => {
  const configs = {
    default: true,
    label: 'My Label',
    element: 'myElement',
  }

  const dispatch = jest.fn();

  const props = {
    configs,
    dispatch
  }
  const checkbox = shallow(
    <CheckBox
      {...props}
    />
  )
  checkbox.find('input').simulate('click')
  expect(dispatch).toHaveBeenCalledWith(update(data))
})