Passing an event object to enzyme .simulate

只愿长相守 提交于 2019-11-27 17:22:21

问题


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

This is my test:

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

This is the input for my component:

<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 think that I need to pass an event as the second object to simulate but I am not sure how to do this.

Thanks


回答1:


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)


来源:https://stackoverflow.com/questions/43921183/passing-an-event-object-to-enzyme-simulate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!