React Answers

How to simulate keydown on document with Jest?

Spread the love

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

For instance, we write

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

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *