This is an easy approach for testing DOM events in hooks/components without actually emmitting/triggering any "fake" events, which is much easier:
- In the tests file, create a dummy React component and call the hook. if the hook is returning something, then assign it to a varaible which should be defined from outside the component so it will be available for the tests cases.
const Dummy = ({focused}) => {
useGlobalEvents(focused, callbackSpy);
return null;
};
- Mock
document.addEventListener
with sinon (globally is preferable):
import sinon from 'sinon';
global.window.addEventListener = sinon.spy();
-
Mount the dummy component (using Enzyme or whichever other React-testing library), so the hook(s) would be called.
-
Test the DOM event by manually firing the callback of the spied-on
addEventListener
:
// get the last call to the "addEventListener" spy
const call = document.addEventListener.lastCall;
// manually call the event handler's callback with the desired `event` argument object, tailored for a specific test:
call.args[1]({code: 'Space'});
// Test the logic inside the event's callback (`useGlobalEvents.js` lines 10-12)
expect(callbackSpy.calledOnce).to.be.true;