将事件对象传递给酶.模拟 [英] Passing an event object to enzyme .simulate

查看:98
本文介绍了将事件对象传递给酶.模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Jest and Enzyme to test a React checkbox component.

这是我的测试

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

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

I get this error however when running the test:

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>

认为 我需要通过一个事件作为simulate 的第二个对象,但我不确定如何执行此操作.

I think that I need to pass an event as the second object to simulate but I am not sure how to do this.

谢谢

推荐答案

simulate 函数采用其他参数,这些参数将传递给事件处理程序.您可以嘲笑您的事件.例如:

simulate function takes other arguments which will be passed to the event handler. You can mock your event. E.g.:

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

这篇关于将事件对象传递给酶.模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆