【问题标题】:Passing an event object to enzyme .simulate将事件对象传递给酶 .simulate
【发布时间】:2017-10-10 19:07:21
【问题描述】:

我正在使用 Jest 和 Enzyme 来测试一个 React 复选框组件。

这是我的测试:

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')
})

但是在运行测试时出现此错误:

TypeError: Cannot read property 'target' of undefined

这是我的组件的输入:

<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>

认为 I need to pass an event as the second object to simulate 但我不知道该怎么做。

谢谢

【问题讨论】:

    标签: javascript reactjs jestjs enzyme


    【解决方案1】:

    simulate 函数接受将传递给事件处理程序的其他参数。您可以模拟您的活动。例如:

    const mockedEvent = { target: {} }
    checkbox.find('input').simulate('click', mockedEvent)
    

    【讨论】:

    • 对我来说这导致TypeError: Cannot set property target of #&lt;Event&gt; which has only a getter
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多