Search code examples
unit-testingangularjsjasmine

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.


Solution

  • 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;
        element.trigger(e);
      };
    

    and then use it in your unit test like so:

    triggerKeyDown(element, 13);
    

    You can see this technique in action in the http://angular-ui.github.io/bootstrap/ project here: https://github.com/angular-ui/bootstrap/blob/master/src/typeahead/test/typeahead.spec.js

    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:

    $.Event('keydown')
    

    to:

    angular.element.Event('keydown')