Can't dispatch KeyboardEvent in Jsdom
See original GitHub issueHi, I’m using jsdom in my unit test, and I need test mouse event and keyboard event. Code like this will trigger click event I bind to “svg” element.
var event = new window.MouseEvent("click");
document.querySelector('svg').dispatchEvent(event);
But code like this will not trigger keydown event I bind to document or body, why?
var event = new window.KeyboardEvent("keydown", {key: "z", char: "z", keyCode: 90});
document.dispatchEvent(event);
It will work in browser, but not work in jsdom. where I was wrong?
Issue Analytics
- State:
- Created 7 years ago
- Reactions:2
- Comments:7 (1 by maintainers)
Top Results From Across the Web
Developers - Can't dispatch KeyboardEvent in Jsdom -
Hi, I'm using jsdom in my unit test, and I need test mouse event and keyboard event. Code like this will trigger click...
Read more >dispatching keyboard event does nothing in Jest test ...
So the problem was that I needed to programatically focus on the input first!
Read more >Simulate Keypress Event - Discuss - ProseMirror
I'm trying to use Jest (JSDOM) to test some keypress events, and your method does work for a registered shortcut. But if the...
Read more >Changelog.md - jest-environment-jsdom-fourteen
JSDOM.fragment() now creates fragments whose document has no browsing context ... Added getModifierState() to MouseEvent and KeyboardEvent .
Read more >The KeyboardEvent
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP,...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
A re-jig of @i8-pi’s example worked for me! I thought I’d post for anybody else who finds their way to this issue 😁
Basically: create a
new window.KeyboardEvent
> dispatch that event ondocument
> 👌In case anybody (like me) finds this old issue because they’re trying to dispatch a keyboard event from a specific node but intending to handle it in the document with
event.target
set appropriately (which is how KeyboardEventHandler works ), there are two things to note:bubbles: true
in the event so that it will bubble to the documentmount()
does not put the component in the document, you need to specifyattachTo:
with a node that’s in the document (React will complain if you try to directly attach todocument.body
)A re-jig of @spen’s code: