如何在AngularJS中测试焦点?

问题描述 投票:2回答:2

请考虑以下skFocus服务:

angular.module('sk.focus', []).service('skFocus', function($timeout) {
  return function(cssSelector) {
    $timeout(function() {
      var element = document.querySelectorAll(cssSelector);

      if (element.length > 0) {
        element[0].focus();
      }
    }, 100);
  };
});

我正在尝试为此服务创建测试:

describe('Service: skFocus', function() {
  beforeEach(module('sk.focus'));

  var $window, $timeout, skFocus;

  beforeEach(inject(function(_$window_, _$timeout_, _skFocus_) {
    $window = _$window_;
    $timeout = _$timeout_;
    skFocus = _skFocus_;

    angular.element(document.body).append('<input id="my-input-field" type="text">');
  }));

  it('Should set focus', function() {
    skFocus('#my-input-field');
    $timeout.flush();

    var $inputElement = $window.jQuery('#my-input-field');

    console.log($inputElement.length);   // 1

    expect($inputElement.is(':focus')).toBe(true);   // Fails!!
  });
});

不幸的是,测试失败。

我在做什么错?

angularjs jasmine karma-runner
2个回答
2
投票

过去,我使用document.activeElement编写了类似的测试,以验证元素是否获得了焦点。


0
投票

我在未触发focus时遇到了类似的问题。就我而言,问题是我在内存HTML中创建了const template = angular.element('<div><input type="text"></div>')模板,但没有将其附加到document.body

在将template附加到<body>之后,focus侦听器开始工作。

© www.soinside.com 2019 - 2024. All rights reserved.