繁体   English   中英

如何正确地对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:");
  });
});

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

您的控制器正在对/ 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 这里
关于下划线

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM