Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

javascript - Passing an event object to enzyme .simulate

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...