Simulate keydown on document for JEST unit testing Simulate keydown on document for JEST unit testing reactjs reactjs

Simulate keydown on document for JEST unit testing


I had the exact same problem and unfortunately couldn't find any details on how to solve this using TestUtils.Simulate. However this issue gave me the idea of simply calling .dispatchEvent with a KeyboardEvent inside my jest tests directly:

var event = new KeyboardEvent('keydown', {'keyCode': 37});document.dispatchEvent(event);

You can find details on the KeyboardEvent here: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent


You can also replace the whole document.eventListener with mock function before you mount the component:

let events;document.addEventListener = jest.fn((event, cb) => {  events[event] = cb;});

And simulate event by calling events[event] after mounting, e.g.:

events.keydown({ keyCode: 37 })

Also, it's quite comfortable to do first part in beforeEach() function if you have many tests dealing with DOM events.


Following @Iris Schaffer answer,If your code makes use of ctrl/alt/shift keys, you will need to init them, as well as mocking implementation of getModifierState method on KeyboardEvent

const keyboardEvent = new KeyboardEvent('keydown', { keyCode, shiftKey, altKey, ctrlKey });jest.spyOn(keyboardEvent, 'getModifierState').mockImplementation((modifier) => {     switch (modifier) {          case 'Alt':               return altKey;          case 'Control':               return ctrlKey;          case 'Shift':               return shiftKey;     }});