Testing for focus an AngularJS directive

All we need is an easy explanation of the problem, so here it is.

How can you test for focus in an AngularJS directive? I would expect the following to work:

describe('focus test', function(){
    it('should focus element', function(){
        var element = $('<input type="text" />');
        // Append to body because otherwise it can't be foccused
        element.appendTo(document.body);
        element.focus();
        expect(element.is(':focus')).toBe(true);
    });
});

However, this only works in IE, it fails in Firefox and Chrome

Update:
The solution by @S McCrohan works. Using this I created a ‘toHaveFocus’ matcher:

beforeEach(function(){
    this.addMatchers({
        toHaveFocus: function(){
            this.message = function(){
                return 'Expected \'' + angular.mock.dump(this.actual) + '\' to have focus';
            };

            return document.activeElement === this.actual[0];
        }
    });
});

Which is used as follows:

expect(myElement).toHaveFocus();

Note that for focus related tests, the compiled element has to be attached to the DOM, which can be done like this:

myElement.appendTo(document.body);

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Try 'document.activeElement' instead of ':focus'. I haven’t tested it in karma, but $('document.activeElement') behaves as desired under standard jQuery.

Method 2

In Jasmine 2, this is now:

beforeEach(function() {
  jasmine.addMatchers({
    toHaveFocus: function() {
      return {
        compare: function(actual) {
          return {
            pass: document.activeElement === actual[0]
          };
        }
      };
    }
  });
});

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply