如何正确单元测试Angular指令

时间:2015-07-07 11:37:21

标签: javascript angularjs unit-testing jasmine karma-runner

我正在尝试测试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:");
  });
});

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

1 个答案:

答案 0 :(得分:2)

您的控制器正在远程调用/ 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()
  });
});

有完整的doco here
关于underscores