Testing Angular directives using events

Testing directives can be somewhat painful at times. I specifically struggled with testing a keyDown event and passing specific keycodes.

I created a basic directive that just checks if specific keyCodes were pressed while an element was active. The general idea was to support keyboard shortcuts within the app. The trouble started when I was trying to write unit tests for the directive and everything I tried and researched just wasn’t working. Introducing jQuery into the test suite would have made the problem go away, but that wasn’t an option.

Ultimately this is the solution I came to:

describe('myApp.handleEpisodePaging', function() {

  var event, element, $scope;


    inject(function(_$rootScope_, _$compile_){
      var $compile = _$compile_;

      $scope = _$rootScope_.$new();
      $scope.load_next_page = jasmine.createSpy('load_next_page');

      element = $compile('<div handle-episode-paging></div>')($scope);

      event = document.createEvent("Events");
      event.initEvent('keydown', true, false);

  it('should handle a keydown event', function(){
    event.keyCode = 82;


The basic premise is that I create a new element using $compile, create an event option and initialize it, and then assign the keyCode value before triggering the event using angular.elements’s trigglerHandler method. Then I can rely on my spy as usual (that gets fired from the actual directive) to ensure everything is working as expected.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s