How to simulate keydown on document with Jest?

To simulate keydown on document with Jest, we create a new KeyboardEvent instance.

For instance, we write

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

to create a new KeyboardEvent instance with the 'keydown' event.

And we set the event object to { keyCode: 37 }.

Then we call document.dispatchEvent with the event object to dispatch the keydown event with key code 37.