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;

beforeEach(module(‘playstation’));

beforeEach(function(){
      
inject(function(\_$rootScope\_, \_$compile\_){
        
var $compile = \_$compile\_;

$scope = \_$rootScope\_.$new();
        
$scope.load\_next\_page = jasmine.createSpy(‘load\_next\_page’);

element = $compile(&#8216;<div handle-episode-paging></div>&#8217;)($scope);

event = document.createEvent("Events");
        
event.initEvent(&#8216;keydown&#8217;, true, false);
      
});
    
});

it(&#8216;should handle a keydown event&#8217;, function(){
      
event.keyCode = 82;
      
element.triggerHandler(event);
      
expect($scope.load_next).toHaveBeenCalled();
    
});

});
  

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.