【问题标题】:How to test values on scope of directive with inline controller如何使用内联控制器测试指令范围的值
【发布时间】:2015-07-15 18:11:55
【问题描述】:

我有以下要单元测试的指令:

'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');
  });
});

【问题讨论】:

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


    【解决方案1】:

    应该是expect(scope.gravatar.email).toEqual('joe@example.com');

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 2015-07-20
      • 1970-01-01
      • 2013-05-28
      • 1970-01-01
      相关资源
      最近更新 更多