在 JEST 单元测试中模拟文档上的 keydown [英] Simulate keydown on document for JEST unit testing
问题描述
使用 JEST
对具有附加到文档的 keydown 侦听器的组件进行单元测试.
Using JEST
to unit test a component that has a keydown listener attached to the document.
我如何在 JEST
中测试这个?如何模拟文档上的 keydown 事件?我需要事件侦听器位于文档上,因为它应该响应键盘操作而不考虑焦点元素.
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.
这里的问题是关于在文档或 document.body 上模拟事件.所有的例子都是关于一个实际的 DOM 节点,它工作正常,但文档没有.
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.
目前正在尝试这样做:
TestUtils.Simulate.keyDown(document, {keyCode : 37}); // handler not invoked
推荐答案
我遇到了完全相同的问题,遗憾的是找不到有关如何使用 TestUtils.Simulate
解决此问题的任何详细信息.但是 这个问题 给了我简单调用 .dispatchEvent
的想法在我的笑话测试中直接使用 KeyboardEvent
:
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);
您可以在此处找到有关 KeyboardEvent
的详细信息:https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent
You can find details on the KeyboardEvent
here: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent
这篇关于在 JEST 单元测试中模拟文档上的 keydown的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!