Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate keydown on document for JEST unit testing

Using JEST to unit test a component that has a keydown listener attached to the document.

How can I test this in JEST? How do I simulate the keydown event on the document? I need the event listener to be on the document since it is supposed to respond the keyboard action irrespective of the focussed element.

EDIT: The question here is about simulating the event on the document or the document.body. All the examples are regarding an actual DOM node, that works fine but the document does not.

Currently trying to do this:

TestUtils.Simulate.keyDown(document, {keyCode : 37}); // handler not invoked
like image 573
Vaibhav Garg Avatar asked Nov 10 '15 19:11

Vaibhav Garg


People also ask

How do you simulate Keydown jest?

To simulate keydown on document with Jest, we create a new KeyboardEvent instance. const event = new KeyboardEvent("keydown", { keyCode: 37 }); document. dispatchEvent(event); to create a new KeyboardEvent instance with the 'keydown' event.

Can jest be used for unit testing?

Jest is an open source JavaScript unit testing framework, used by Facebook to test all JavaScript code including React applications.

Does jest work with JavaScript?

Jest is a delightful JavaScript Testing Framework with a focus on simplicity. It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!


2 Answers

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

like image 130
Iris Schaffer Avatar answered Oct 17 '22 16:10

Iris Schaffer


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.

like image 4
andrianov Avatar answered Oct 17 '22 16:10

andrianov