小编Mar*_*ijk的帖子

测试焦点AngularJS指令

如何在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);
    });
});
Run Code Online (Sandbox Code Playgroud)

但是,这仅适用于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];
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

使用如下:

expect(myElement).toHaveFocus();
Run Code Online (Sandbox Code Playgroud)

请注意,对于与焦点相关的测试,已编译的元素必须附加到DOM,可以这样做:

myElement.appendTo(document.body);
Run Code Online (Sandbox Code Playgroud)

jasmine angularjs angularjs-directive karma-runner

22
推荐指数
2
解决办法
6821
查看次数