如何用内联控制器测试指令范围上的值

How to test values on scope of directive with inline controller

本文关键字:范围 指令 测试 何用内 控制器      更新时间:2023-09-26

我有以下指令,我想进行单元测试:

'use strict';
angular.module('gameApp')
  .directive('gmGravatar', gmGravatar);
gmGravatar.$inject = ['$routeParams', 'playersService'];
function gmGravatar() {
  var directive = {
    restrict: 'E',
    template: '<img gravatar-src="gravatar.email" alt="" id="gravatar" class="img-rounded" style="margin: auto; display: block;">',
    controller: function($routeParams, playersService) {
      var vm = this;
      var playerId = $routeParams.playerId;
      playersService.getPlayerInfo({
        playerId: playerId
      }).$promise.then(function(player) {
        vm.email = player.email;
      });
    },
    controllerAs: 'gravatar'
  };
  return directive;
}

我已经成功地设置了我的测试规范,并让我的第一个断言通过了。然而,我正在努力如何测试vm.email:

'use strict';
describe('gmGravatar directive', function() {
  var element;
  var scope;
  var $httpBackend;
  beforeEach(module('gameApp'));
  beforeEach(module('templates'));
  beforeEach(inject(function($rootScope, $compile, _$httpBackend_) {
    scope = $rootScope.$new();
    element = '<gm-gravatar></gm-gravatar>';
    element = $compile(element)(scope);
    $httpBackend = _$httpBackend_;
    $httpBackend.whenGET('/api/players/playerInfo').respond(200, '');
    scope.$digest();
  }));
  it('should replace the element with the appropriate content', function() {
    expect(element.html()).toContain('<img gravatar-src="gravatar.email"');
    expect(scope.email).toEqual('joe@example.com');
  });
});

可能是expect(scope.gravatar.email).toEqual('joe@example.com');

也可以试试expect(element.scope().gravatar.email).toEqual('joe@example.com');