我有以下指令来自动对焦字段:
.directive('ngAutofocus', function ($timeout) {
return {
restrict: 'A',
link: function (scope, elm) {
$timeout(function () {
elm[0].focus();
});
}
};
}
我如何对此进行单元测试?我尝试了几个像下面的选择器,但它们都返回错误或错误:
console.log($(elm[0]).is(':focus'));
我的单元测试设置如下:
elm = angular.element('<input type="text" name="textfield1" ng-autofocus>');
$scope.$digest();
$compile(elm)($scope);
答案 0 :(得分:33)
我明白了,实际上很明显;
it('should set the focus on timeout', function () {
spyOn(elm[0],'focus');
$timeout.flush();
expect(elm[0].focus).toHaveBeenCalled();
})
我的问题有两方面:
答案 1 :(得分:3)
您可以使用document.activeElement
来检查焦点。唯一的缺点是需要将HTML添加到文档正文中才能实现。
https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement
答案 2 :(得分:0)
下面更详细的解决方案,允许测试(监视)立即运行的焦点(即没有$timeout
或其他事件)。关键是在DOM element
运行之前首先呈现$compile
:
'use strict';
describe('Testing the focus call from the link function', function () {
var $compile;
var $rootScope;
beforeEach(angular.mock.module('auto-focus-module'));
beforeEach(inject(function (_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('should automatically focus when calling the link function', function () {
var $scope = $rootScope.$new();
// create an uncompiled DOM element so we can bind the focus spy
var rawEl = angular.element('<input auto-focus-directive>');
// set the spy
spyOn(rawEl[0], 'focus');
// compile the rawEl so that compile and link functions run
$compile(rawEl)($scope);
expect(rawEl[0].focus).toHaveBeenCalled();
});
});
使用directive
和link
功能可能如下所示:
(function () {
'use strict';
angular.module('auto-focus-module')
.directive('autoFocusDirective', autoFocusDirective);
function autoFocusDirective () {
return {
link: link
};
function link (scope, elem) {
elem[0].focus();
}
}
})();
答案 3 :(得分:-3)
你应该使用angular.element api - jQuery lite - 并使用方法triggerHandler()。
it('should have focus', function() {
elm.triggerHandler('focus');
expect(elm).toBeInFocus() //PSEUDO CODE - you will need to see how this can be tested
}
http://docs.angularjs.org/api/ng/function/angular.element
http://api.jquery.com/triggerhandler/
某些测试重点知识的潜在领域:
https://shanetomlinson.com/2014/test-element-focus-javascript
另外,关于您的单元测试 - 您不需要将元素附加到身体上,没有它可以进行测试。