模拟文档上的按键,以进行JEST单元测试 [英] Simulate keydown on document for JEST unit testing

查看:563
本文介绍了模拟文档上的按键,以进行JEST单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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解决此问题的详细信息.但是此问题使我想到了简单地在内部使用KeyboardEvent调用.dispatchEvent的想法.我的笑话直接测试:

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/zh-CN/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单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆