测试焦点 AngularJS 指令 [英] Testing for focus an AngularJS directive
问题描述
如何在 AngularJS 指令中测试焦点?我希望以下内容起作用:
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);
});
});
然而,这只适用于 IE,它在 Firefox 和 Chrome 中失败
However, this only works in IE, it fails in Firefox and Chrome
更新:@S McCrohan 的解决方案有效.我使用它创建了一个toHaveFocus"匹配器:
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];
}
});
});
用法如下:
expect(myElement).toHaveFocus();
请注意,对于焦点相关的测试,编译的元素必须附加到 DOM,可以这样完成:
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);
推荐答案
尝试 'document.activeElement'
而不是 ':focus'
.我还没有在 karma 中测试过它,但是 $('document.activeElement')
在标准 jQuery 下表现得如其所愿.
Try 'document.activeElement'
instead of ':focus'
. I haven't tested it in karma, but $('document.activeElement')
behaves as desired under standard jQuery.
这篇关于测试焦点 AngularJS 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!