Testing for focus an AngularJS directive

风格不统一 提交于 2019-12-03 10:58:26

问题


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);

回答1:


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




回答2:


In Jasmine 2, this is now:

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


来源:https://stackoverflow.com/questions/18850219/testing-for-focus-an-angularjs-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!