如何在 AngularJS 指令中测试焦点?我希望以下工作:
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);
    });
});
但是,这只适用于 IE,它在 Firefox 和 Chrome 中失败
更新:@S McCrohan 的解决方案有效。使用它我创建了一个“toHaveFocus”匹配器:
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];
        }
    });
});
使用如下:
expect(myElement).toHaveFocus();
请注意,对于焦点相关的测试,编译后的元素必须附加到 DOM,可以这样完成:
myElement.appendTo(document.body);