Testing focus() on an element in an AngularJS directive template
Asked Answered
S

1

6

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've tested that the focus watcher works in a browser, but I'd like to be able to trigger it in a unit test. This is what I've tried but it isn't working.

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

I can see that I am correctly getting to the input box with the find call, and I would expect that code to trigger the focus event on the input box, but nothing is happening. What am I missing here?

Scarface answered 28/1, 2014 at 16:17 Comment(8)
I don't think you need to do element.find('input') the element is the input tagIrredeemable
Replace is set to false. element is the div and contained within it is the input tag.Scarface
Oh, I missed that partIrredeemable
Try element.find('input').triggerHandler('focus');Irredeemable
No such luck with $(element.find('input')[0]).triggerHandler('focus');Scarface
Sorry didn't read what you said. I did exactly that and it worked. Any thoughts on filling in with text?Scarface
Let me post a answer as it could help other peopleIrredeemable
element.find('input').val('hello world'). Kindly accept as answer when you can.Irredeemable
I
18

When trying to trigger events on angular elements, one should use the triggerHandler() function which is just really jqLite function and not angulars and then pass in the event as a string parameter as shown below.

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

To perform any other functions on an angular element, read the documentation here, it shows you a list of functions available to angular elements

Irredeemable answered 28/1, 2014 at 16:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.