Testing focus () on an element in an AngularJS directive template

Given the following directive

directive('myDirective', function() { return { restrict: 'A', scope: {}, replace: false, template: '<input ng-focus="onFocus()" type="text" />', link: function(scope, element, attr) { scope.onFocus = function() { console.log('got focus'); }; } }; }); 

I tested that the focus observer works in the browser, but I would like to run it in the unit test. This is what I tried, but it does not work.

 var element = angular.element('<div my-directive></div>'); $compile(element)($scope); $scope.$digest(); element.find('input')[0].focus(); 

I see that I got into the input field correctly with the find call, and I would expect this code to trigger a focus event in the input field, but nothing happens. What am I missing here?

+6
source share
1 answer

When trying to trigger events on angular elements, you should use the triggerHandler () function, which is actually a jqLite function, not an angular one, and then pass it as an argument to the event, as shown below.

 element.find('input').triggerHandler('focus'); 

To execute any other functions in an angular element, read the documentation here , it shows you a list of functions available for angular elements

+17
source

All Articles