How to test focus in AngularJS?

孤者浪人 提交于 2019-12-11 01:02:48

问题


Consider the following skFocus service:

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

I'm trying to create a test for this service:

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

Unfortunately, the test fails.

What am I doing wrong?


回答1:


In the past I wrote similar tests using document.activeElement to verify that an element received focus.



来源:https://stackoverflow.com/questions/24196072/how-to-test-focus-in-angularjs

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