views:

651

answers:

1

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.

+4  A: 

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.

geowa4
That works great. Thanks.
RaYell
Good answer, but this does not seem to work with triggerEvent(), which is more useful when testing for the return value of a handler.
Max Shawabkeh