Skip to content Skip to sidebar Skip to footer

Angular: How To Spy On $element.on

I have a directive which does something like this in its link function angular.module('myApp') .directive('barFoo', function() { return { restrict: 'E',

Solution 1:

Link function can be tested separately

element = angular.element('<bar-foo');
spyOn(element, 'on');
BarFooDirective[0].link(scope, element);
expect(element.on).toHaveBeenCalled();

if it is simple enough (stays away from attrs, required controllers, dependencies), otherwise the spec will cause more problems than it can solve.

Otherwise, it can be tested like it is done by the framework:

element = angular.element('<bar-foo');
expect(angular.element._data(element[0]).events.click).toBeDefined();

For real-world directive which may have more than one click listener defined in either itself or child directives it is not enough to make sure that listeners exist. Generally you may want to encapsulate internal functions, but anonymous click handler can also be exposed to scope for the purpose of testing:

element = angular.element('<bar-foo');
expect(angular.element._data(element[0]).events.click).toContain(scope.onClick);

Solution 2:

Well, it's not necessary to test on method. You can test event bindings with the help of triggerHandler()

link: function (scope, element) {
    element.on('click', 'something to heppen');
}

Test:

element = angular.element('<bar-foo></bar-foo>');
$compile(element)(scope); 
$(element[0]).triggerHandler('click');
expect('something binded to click event to happen');

Solution 3:

If you've compiled your element in in a beforeEach like this:

myEl = '<div my-el>MY EL</div>';
scope = $rootScope.$new();
directiveElement = $compile(myEl)(scope);
scope.$digest();

Try replacing mousedown with the event you are testing like this:

expect(directiveElement.on.mousedown).toBeDefined;

Post a Comment for "Angular: How To Spy On $element.on"