Angularjs 设置焦点的测试指令
指令:Angularjs 设置焦点的测试指令,angularjs,jasmine,Angularjs,Jasmine,指令: 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) {
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');
});
}
}
);
}
};
测试规格:
描述('指令:焦点',功能(){
var$timeout,element,$scope,$compile;
beforeach(函数(){
模块(“tdsapp”);
注入(函数($timeout,$rootScope,$compile){
$timeout=$timeout;
$compile=\$compile;
$scope=$rootScope.$new();
});
});
它('should call focus on element',function(){
var elm=角度元素(“”);
spyOn(elm[0],“focus”);
$timeout.flush();
expect(elm[0].focus.tohavebeencall();
});
}))
我看了又看,都不管用。我得到expect failing或$timeout.flush()-没有要刷新的延迟任务
编辑:
正如我在本文中所说的,上面的两个示例不起作用。这对我来说不起作用。答案的可能副本清楚地表明元素需要使用$compile服务进行编译。
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();
});