如何检查我的元素已在单元测试被集中 [英] How do I check if my element has been focussed in a unit test
本文介绍了如何检查我的元素已在单元测试被集中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下的指令自动对焦字段:
.directive('ngAutofocus',函数($超时){
返回{
限制:'A',
链接:功能(范围,榆){
$超时(函数(){
榆树[0]。重点();
});
}
};
}
如何将我的单元测试吗?我试过几件事情像下面的选择,但他们都返回错误或虚假的:
的console.log($(榆[0])是(':聚焦'));
我的单元测试的设置是这样的:
榆树= angular.element('<输入类型=文本名称=textfield1的NG-自动对焦>');
$ $范围摘要()。
$编译(榆树)($范围内);
解决方案
我想通了,这是pretty实际上明显;
它('应该将重点放在超时',函数(){
spyOn(榆[0],聚焦);
$ timeout.flush();
期待(榆树[0]。重点).toHaveBeenCalled();
})
我的问题是双重的:
- 我没有打电话超时冲洗功能,因此超时不存在的,而
- 我是想看看元素的焦点属性,而只是看着对焦()函数的调用更像单元测试。焦点属性的东西,确实属于端到端测试的领土。
I have the following directive to autofocus a field:
.directive('ngAutofocus', function ($timeout) {
return {
restrict: 'A',
link: function (scope, elm) {
$timeout(function () {
elm[0].focus();
});
}
};
}
How would I unit test this? I tried several things like the following selector but they all return errors or false:
console.log($(elm[0]).is(':focus'));
My unit test is set up like this:
elm = angular.element('<input type="text" name="textfield1" ng-autofocus>');
$scope.$digest();
$compile(elm)($scope);
解决方案
I figured it out, and it was pretty obvious actually;
it('should set the focus on timeout', function () {
spyOn(elm[0],'focus');
$timeout.flush();
expect(elm[0].focus).toHaveBeenCalled();
})
My problem was two-fold:
- I wasn't calling the timeout flush function so timeout wasn't occuring, and
- I was trying to look at the focus attribute of the element whereas just looking at the call of the focus() function is much more like unit-testing. The focus attribute is something that really belongs to the e2e testing territory.
这篇关于如何检查我的元素已在单元测试被集中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文