Chandra Chandra - 9 months ago 110
AngularJS Question

How do I trigger a keyup/keydown event in an angularjs unit test?

I want to unit test a directive that emulates a placeholder, where the input value is cleared only on keyup/down events.


You need to create an event programatically and trigger it. To do so including jQuery for unit tests is quite useful. For example, you could write a simple utility like this:

  var triggerKeyDown = function (element, keyCode) {
    var e = $.Event("keydown");
    e.which = keyCode;

and then use it in your unit test like so:

triggerKeyDown(element, 13);

You can see this technique in action in the project here:

Disclaimer: let's be precise here: I'm not advocating using jQuery with AngularJS! I'm just saying that it is a useful DOM manipulation utility for writing tests interacting with the DOM.

To make the above code work without jQuery, change: