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
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.
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.
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.
Try this
link.simulate('click', { preventDefault: () => { } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With