/ jest

How to mock event.preventDefault() with Jest

Level - Intermediate. Read Time ~ <3 minutes.

This evening I've been starting work on converting unit tests from Mocha to Jest. The reason for doing this is that Jest runs test in parallel, handles ES6 code better, gives a better output and I just want to learn it.

When I had my tests in Mocha, for stubbing and mocking I used Sinon. This is a perfectly good library, but Jest has this functionality out of the box, so it's not necessary to have this as an additional dependency. Jest offers a mock in the form of jest.fn();. I struggled as I was trying to use this for stubbing out event.preventDefault() in an event handler in a React component. The proper way to do this is demonstrated in the below Gist, using jest.spyOn(objectToSpyOn, 'functionToSpyOn()').

Any questions or corrections required get in touch.