AngularJS:如何测试给予元素焦点的指令?
注意:建议的链接是对有关服务的问题的回答,没有对如何解决此问题给出明确解释AngularJS:如何测试给予元素焦点的指令?,angularjs,angularjs-directive,karma-runner,karma-jasmine,Angularjs,Angularjs Directive,Karma Runner,Karma Jasmine,注意:建议的链接是对有关服务的问题的回答,没有对如何解决此问题给出明确解释 element = angular.element('<form><input type="text" name="first" /><input type="text" name="second" autofocus="true" /></form>'); $compile(element)(scope); scope.$digest(); 我正在尝试为我的简单(和工
element = angular.element('<form><input type="text" name="first" /><input type="text" name="second" autofocus="true" /></form>');
$compile(element)(scope);
scope.$digest();
我正在尝试为我的简单(和工作)AngularJSautofocus
指令设置一个业力测试:
app.directive('autofocus', function ($timeout) {
return {
replace: false,
link: function (scope, element, attr) {
scope.$watch(attr.autofocus,
function (value) {
if (value) {
$timeout(function () {
element[0].focus();
console.log('focus called');
});
}
}
);
}
};
});
这是我目前的测试:
describe('The autofocus directive', function () {
var timeout;
beforeEach(module('myApp'));
beforeEach(inject(function($timeout) {
timeout = $timeout;
}));
it('should set focus to first autofocus element', function () {
var form = angular.element('<form />');
var input1 = angular.element('<input type="text" name="first" />');
var input2 = angular.element('<input type="text" name="second" autofocus="true" />');
form.append(input1);
form.append(input2);
spyOn(input2[0], 'focus');
timeout.flush();
expect(input2[0].focus).toHaveBeenCalled();
});
在spyOn(输入[0],'focus')之后,
测试当然成功了,但这不是我想要的
最后一个问题是:如何测试将焦点设置为元素的指令?当您仅在单元测试中调用angular.element时,angular将不理解“自动聚焦”是一个指令。因此,在代码中:
var form = angular.element('<form />');
var input1 = angular.element('<input type="text" name="first" />');
var input2 = angular.element('<input type="text" name="second" autofocus="true" />');
form.append(input1);
form.append(input2);
并创建新模板
element = angular.element('<form><input type="text" name="first" /><input type="text" name="second" autofocus="true" /></form>');
$compile(element)(scope);
scope.$digest();
通过这种方式,angular将理解“autofocus”是一个指令,并将您创建的所有事件分配给“autofocus”正在处理的元素
焦点事件的测试我遵循以下参考:
该问题的可能重复是针对某项服务,而答案不太清楚,对我来说…:-(把这个扔进一个JSFIDLE?如果我们看到它失败了,就更容易处理。当然:这是小提琴:(虽然这是我的第一把茉莉花小提琴,但我不知道它是否合适…:-)。我已经更新了小提琴,现在它将通过。尝试类似的方法。参考: