Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test jQuery keyboard events?

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.

like image 569
RaYell Avatar asked Jul 20 '09 15:07

RaYell


1 Answers

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.

like image 184
geowa4 Avatar answered Nov 07 '22 17:11

geowa4