Simulate keydown on document for JEST unit testing

橙三吉。 提交于 2019-12-05 02:32:45

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!