【问题标题】:Triggering this.props.dispatch in a test environment在测试环境中触发 this.props.dispatch
【发布时间】:2017-05-13 22:22:58
【问题描述】:

您好,我有一个像这样的 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 参与我的测试?

谢谢

【问题讨论】:

  • 请展示整个 Checkbox 组件,以便我们了解“this.props.dispatch(update(data))”是如何发挥作用的。

标签: javascript reactjs jestjs enzyme


【解决方案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))
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 2023-03-07
    • 2016-07-09
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多