如何正确地对 Angular 指令进行单元测试

How to properly unit test Angular directive

我正在尝试测试 Angular 指令,但 运行 出现以下错误:

Error: Unexpected request: GET /api/players/info

我相信这是因为在我的指令定义对象中引用了我的控制器,但我不确定如何处理它。下面是我的指令,然后是我的测试:

playerInfo.directive.js:

'use strict';

angular.module('gameApp')
  .directive('playerInfo', playerInfo);

function playerInfo() {
  var directive = {
    link: link,
    restrict: 'E',
    templateUrl: '/app/player/playerInfo.directive.html',
    controller: 'PlayerInfoController',
    controllerAs: 'playerInfo'
  };
  return directive;

  function link(scope, element) {
    var address =   angular.element(element[0].getElementsByClassName('blur'));
    address.on('click', function() {
      address.css({'-webkit-filter': 'none'});
    });
  }
}

playerInfoSpec.js:

'use strict';

describe('playerInfo directive', function() {
  var element;
  var scope;

  beforeEach(module('gameApp'));

  beforeEach(inject(function($templateCache) {
    var templateUrl = '/app/player/playerInfo.directive.html';
    var asynchronous = false;
    var req = new XMLHttpRequest();
    req.onload = function() {
      $templateCache.put(templateUrl, this.responseText);
    };
    req.open('get', '/base' + templateUrl, asynchronous);
    req.send();
  }));

  beforeEach(inject(function($rootScope, $compile) {
    scope = $rootScope.$new();
    element = '<player-info></player-info>';
    element = $compile(element)(scope);
  }));

  it('should replace the element with the appropriate content', function() {
    scope.$digest();
    expect(element.html()).toContain("Score:");
  });
});

我的控制器使用注入服务向 /api/players/info 发送 GET 请求,这就是为什么我认为此错误与我的指令定义对象中的控制器引用有关。

您的控制器正在远程调用 /api/players/info。 在单元测试时(我猜你正在使用 Karma 和 Jasmine),你将不得不使用 ngMock 模块和 $httpBackend 服务来模拟远程调用。

'use strict';

describe('playerInfo directive', function() {
  var element;
  var scope;
  var $httpBackend

  beforeEach(module('gameApp'));

  beforeEach(inject(function($templateCache) {
    var templateUrl = '/app/player/playerInfo.directive.html';
    var asynchronous = false;
    var req = new XMLHttpRequest();
    req.onload = function() {
      $templateCache.put(templateUrl, this.responseText);
    };
    req.open('get', '/base' + templateUrl, asynchronous);
    req.send();
  }));

  beforeEach(inject(function($rootScope, $compile, _$httpBackend_) {
    scope = $rootScope.$new();
    element = '<player-info></player-info>';
    element = $compile(element)(scope);
    $httpBackend = _$httpBackend_;
    $httpBackend.whenGET('/api/players/info').respond(200, '');
  }));

  it('should replace the element with the appropriate content', function() {
    scope.$digest();
    expect(element.html()).toContain("Score:");
    $httpBackend.flush()
  });
});

有完整的文档here
关于 underscores