AngularJS:如何测试赋予元素焦点的指令?

Mar*_*coS 3 angularjs angularjs-directive karma-runner karma-jasmine

注意:建议的链接是有关服务问题的答案,并未就如何解决此问题给出明确说明

我正在尝试为我的简单(和工作)AngularJS autofocus指令设置业力测试:

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');
            });
          }
        }
      );
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

这是我目前的测试:

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();
  });
Run Code Online (Sandbox Code Playgroud)

这是(FAILED)输出karma:

$ node_modules/karma/bin/karma start test/karma.conf.js
INFO [karma]:Karma v0.12.23服务器在http:// localhost:8080/
INFO [launcher]启动:启动浏览器PhantomJS
INFO [PhantomJS 1.9.8 (Linux)]:连接到套接字U34UATs8jZDPB74AXpqR,ID为96802943
PhantomJS 1.9.8 (Linux):执行0 of 20 SUCCESS(0秒/ 0秒)
PhantomJS 1.9.8(Linux)自动聚焦指令应将焦点设置为第一个自动对焦元素FAILED
期待的间谍焦点被称为.
PhantomJS 1.9.8(Linux):执行20 of 20(1失败)(0.156秒/0.146秒)


只是添加

input[0].focus();
Run Code Online (Sandbox Code Playgroud)

spyOn(input[0], 'focus')当然,在测试成功之后,但这不是我想要的......


最后一个问题是:我如何对一个将焦点设置为一个元素的指令进行业力测试?

the*_*h92 5

当你只在单元测试中调用angular.element时,Angular不会理解"autofocus"是一个指令.因此,在您的代码中:

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);
Run Code Online (Sandbox Code Playgroud)

Angular不会将自动聚焦设置为指令,也不会分配与您已声明的"autofocus"指令相关的任何内容.为了在单元测试中执行此操作,您必须使用$ compile为其分配范围.您可以将小提琴改为像这样通过测试:

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

如您所见,我创建了一个新范围

scope = $rootScope.$new();
Run Code Online (Sandbox Code Playgroud)

并创建一个新模板

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

并将创建的范围分配给此新模板

$compile(element)(scope);
scope.$digest();
Run Code Online (Sandbox Code Playgroud)

通过这种方式,angular将理解"autofocus"是一个指令,并将您创建的所有事件分配给"autofocus"正在处理的元素.

对焦点事件的测试我遵循了这个参考:

如何检查我的元素是否已集中在单元测试中