Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an event object to enzyme .simulate

Tags:

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

like image 583
SeanPlusPlus Avatar asked May 11 '17 16:05

SeanPlusPlus


People also ask

How do you simulate an event in react?

Simulate a Click Event First, we import the needed functions from @testing-library/react . In our test, we call render from that library, passing in the usage of our Button component. React Testing Library handles setting up the DOM for test then rendering into that DOM.


1 Answers

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) 
like image 104
madox2 Avatar answered Nov 20 '22 01:11

madox2