测试指令时如何处理控制器依赖

How to deal with controller dependencies when testing directives

我正在使用以下规范测试 Angular 指令:

'use strict';

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

  beforeEach(module('gameApp'));
  beforeEach(module('templates'));

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

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

和我的指令:

'use strict';

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

function playerInfo() {
  var directive = {
    link: link,
    restrict: 'E',
    replace: true,
    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'});
    });
  }
}

我一直看到的错误是 TypeError: 'undefined' is not an object (evaluating 'moment.utc')

编辑:毕竟不是我的控制器导致了这个问题。我在指令的 HTML 模板中使用了两次 angular-moment 指令:

<div>{{playerInfo.game.date | amDateFormat: 'MMMM Do, YYYY'}} - <b am-time-ago="playerInfo.game.date"></b></div>

这似乎是导致错误的原因,但我不确定如何解决它。我已将 src/assets/bower_components/moment/moment.jssrc/assets/bower_components/angular-moment/angular-moment.js 添加到 karma.config.jsfiles 数组中。

问题是我在 karma.config.js 中声明必要文件的顺序。 moment 需要在 angular-moment 之前来:

files: [
  ...
  'src/assets/bower_components/moment/moment.js',
  'src/assets/bower_components/angular-moment/angular-moment.js',
  ...
],