用于测试的重点指令AngularJS [英] Testing for focus an AngularJS directive
问题描述
你怎么能在AngularJS指令测试的重点是什么?我希望以下工作:
描述(重点测试,函数(){
它('应重点元素,函数(){
VAR元= $('<输入类型=文本/>');
//附加到身体,因为否则它不能被foccused
element.appendTo(document.body的);
element.focus();
期待(element.is(':聚焦'))TOBE(真)。
});
});
不过,在IE浏览器这只是工作,在Firefox和Chrome失败
更新:
通过@S McCrohan解决方案的工作。使用这个我创建了一个toHaveFocus'匹配:
beforeEach(函数(){
this.addMatchers({
toHaveFocus:功能(){
this.message =功能(){
返回'预期的\\''+ angular.mock.dump(this.actual)+\\有重点;
}; 返回document.activeElement === this.actual [0];
}
});
});
哪个的使用如下:
预期(myElement).toHaveFocus();
请注意,对于焦点相关的测试,已编译的元件具有被连接到DOM,其可以这样来完成:
myElement.appendTo(document.body的);
尝试'document.activeElement
而不是:注重
。我没有因果报应测试,但 $('document.activeElement')
下的行为标准的jQuery应有的作用。
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);
Try 'document.activeElement'
instead of ':focus'
. I haven't tested it in karma, but $('document.activeElement')
behaves as desired under standard jQuery.
这篇关于用于测试的重点指令AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!