Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock e.preventDefault in react component's child

Hy, I don't know how to mock an inline function in React component's child

My stack: sinon, chai, enzyme;

Component usage:

<ListItem onClick={() => someFn()} /> 

Component's render:

render() {     return (       <li>         <a href="#" onClick={e => {             e.preventDefault();             this.props.onClick();           }}         > whatever </a>       </li>     );   } 

Here we have onClick function that calls e.preventDefault(). How to tell to <a href>(link) to not to call e.preventDefault()? How can I mock an onClick?

Below is what I have tried in tests:

Shallow copy setup

function setup() {   const someFn = sinon.stub();    const component = shallow(     <ListItem       onClick={() => {         someFn();       }}     />   );    return {     component: component,     actions: someFn,     link: component.find('a'),     listItem: component.find('li'),   } } 

And the test

  it('simulates click events', () => {     const { link, actions } = setup();     link.simulate('click'); //Click on <a href>     expect(actions).to.have.property('callCount', 1); //will be fine if we remove e.preventDefault()   }); 

Test's output error:

TypeError: Cannot read property 'preventDefault' of undefined 
like image 446
Sergei Panfilov Avatar asked Jan 24 '17 13:01

Sergei Panfilov


People also ask

How do you test for preventDefault in jest?

preventDefault being called by assigning a property to that initialised event: test('prevents default on click', () => { const {getByText} = render(<MyComponent />); const button = getByText(/click me/); // initialise an event, and assign your own preventDefault const clickEvent = new MouseEvent('click'); Object.

What is e preventDefault () in react?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

Does preventDefault stop propagation?

Event.preventDefault()The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation() , either of which terminates propagation at once.


1 Answers

Try this

link.simulate('click', {   preventDefault: () => {   }  }); 
like image 185
WitVault Avatar answered Sep 21 '22 17:09

WitVault