AngularJS: how to test directive which gives focus to element?

天大地大妈咪最大 提交于 2019-12-05 22:55:12
themyth92

When you call angular.element only in unit test, Angular will not understand the "autofocus" is a directive. Therefore, in your code :

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);

Angular will not set autofocus as a directive and will not assign anythings relating to the "autofocus" directive that you have already declared. In order to do this in unit test, you have to use $compile to assign it with a scope. You can change the fiddle to like this to pass the test:

http://jsfiddle.net/ksqhmkqm/1/.

As you can see, I have created a new scope

scope = $rootScope.$new();

And create a new template

element = angular.element('<form><input type="text" name="first" /><input type="text" name="second" autofocus="true" /></form>');

And assign the created scope to this new template

$compile(element)(scope);
scope.$digest();

With this way, angular will understand the "autofocus" is a directive and assign all the event that you have created to this element that "autofocus" is working on.

The testing for the focus event I have followed this reference:

How do I check if my element has been focussed in a unit test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!