指令:
angular
.module('tdsapp')
.directive('focus', focus);
focus.$inject = ['$timeout'];
// Used to set focus on element
function focus($timeout) {
return {
scope: { focus: '@'},
link: function (scope, element) {
scope.$watch('focus',
function (value) {
if (value) {
$timeout(function () {
element[0].focus();
console.log('focus called');
});
}
}
);
}
};
测试规格: describe('指令:focus',function(){
var $timeout, element, $scope, $compile;
beforeEach(function () {
module('tdsapp');
inject(function (_$timeout_, $rootScope, _$compile_) {
$timeout = _$timeout_;
$compile = _$compile_;
$scope = $rootScope.$new();
});
});
it('should call focus on element', function () {
var elm = angular.element('<input type="text" name="second" focus="true" />');
spyOn(elm[0], 'focus');
$timeout.flush();
expect(elm[0].focus).toHaveBeenCalled();
});
});
我查看了AngularJS: how to test directive which gives focus to element?和How do I check if my element has been focussed in a unit test,但都没有效果。我得到了期望失败或$ timeout.flush() - 没有要刷新的延期任务。
编辑:
正如我在文中所述 - 以上两个例子不起作用。