How to unit test jQuery keyboard events?

Is there a way to check Java keyboard event handlers (for keypress , keyup , keydown )?

I know that I can declare event handlers as follows:

 function keyUpEvHandler(e) { ... // code here } $('#myId').keyup(keyUpEvHandler); 

and then just run this function in unit tests, but I will have to prepare the event argument object the same as when pressing the actual key:

 var e = {keyCode: 70, ...}; 

Is there a way to raise this event and pass key code as an argument or something similar? Unfortunately jQuery trigger () docs does not apply to keyboard events.

+7
jquery events unit-testing qunit keyboard-events
source share
1 answer

You can pass arbitrary data through an event object.

Documentation:

 var event = jQuery.Event("logged"); event.user = "foo"; event.pass = "bar"; $("body").trigger(event); 

What can you do:

 var event = jQuery.Event("keyup"); event.keyCode = 72; $(".selector").trigger(event); 

Thus, the event passed to the handler (s) will have a keyCode parameter according to what you want.

+15
source share

All Articles