Is there a way to test JavaScript keyboard event handlers (for keypress
, keyup
, keydown
events)?
I know I can declare event handlers like this:
function keyUpEvHandler(e) {
... // code here
}
$('#myId').keyup(keyUpEvHandler);
and then just run this function in unit tests, but I will have to prepare event argument object to be the same as passed when actual key is pressed:
var e = {keyCode: 70, ...};
Is there any way to trigger this event and pass key code as an argument or something similar? Unfortunately jQuery trigger() docs doesn't cover keyboard events.
You can pass arbitrary data through the event object.
The docs:
var event = jQuery.Event("logged");
event.user = "foo";
event.pass = "bar";
$("body").trigger(event);
What you can do:
var event = jQuery.Event("keyup");
event.keyCode = 72;
$(".selector").trigger(event);
This way, the event passed to the handler(s) will have the keyCode
set to whatever you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With