使用ControllerAs测试指令角度

时间:2016-03-09 02:55:21

标签: angularjs unit-testing karma-jasmine

我试图测试指令。使用controllerAs创建一个顶级范围,我们可以访问它的属性。但是在调试时我尝试访问element.scope()。property - 我得到了undefined。任何有关为什么的帮助将不胜感激。

- BugDirective

 (function() {
  'use strict';

  angular
    .module('debug-blog-app')
    .directive('avBug', avBug);

  function avBug() {
    return {
        restrict: 'E',
        templateUrl: 'views/directives/bug.html',
        scope: {
          bug: '='
        },
        controller: BugFormController,
        controllerAs: 'bugCtrl',
        bindToController: true
    };
  };

  BugFormController.$inject = ['$window', '$scope', 'BugService'];
  function BugFormController($window, $scope, BugService) {
    var vm = this;

    vm.updateBug = function(){
      BugService.updateBug(vm.bug);
    };

    vm.deleteBug = function(){
      if($window.confirm("Delete the Bug?!")){
        return BugService.deleteBug(vm.bug.id)
          .then(function(){
            $scope.$emit('bug.deleted', vm.bug);
          });
      }
    };
  };
})();

- 规格

'use strict'

describe('avBug Directive', function () {
    var bugCtrl,
        element,
        BugService,
        $scope,
        $rootScope;

    beforeEach(module('app'));

    beforeEach(inject(function($q, $compile, _$rootScope_, _BugService_) {
        $rootScope = _$rootScope_;


        var directiveMarkup = angular.element("<av-bug></av-Bug>");
        element = $compile(directiveMarkup)($rootScope);
        bugCtrl = element.scope().bugCtrl;


        BugService = _BugService_;


        spyOn(BugService, 'deleteBug').and.callFake(function() {
            var deferred = $q.defer();
            deferred.resolve('data');
            return deferred.promise;
        });

        spyOn($rootScope,'$emit').and.callThrough();
    }));

    it('should delete a bug', function() {
        bugCtrl.deleteBug(0);
        expect(BugService.deleteBug).toHaveBeenCalledWith(0);
        $rootScope.$digest();
        expect($rootScope.$emit).toHaveBeenCalledWith('bug.deleted');
    });
});

- index.html的

<div class="container">
  <div ui-view></div>
</div>

- home.html的

<av-bug bug="bug" ng-repeat="bug in homeCtrl.bugs"></av-bug>

2 个答案:

答案 0 :(得分:1)

为了单元测试的目的,我还要补充一点,你可以使用@Ramy Deeb发布的相同功能获得父控制器。

set.fill = ChartFill.fillWithLinearGradient(gradient!, angle: 180.0)

为了测试元素隔离范围,只需获取

vm = element.scope().$$childTail.nameOfParentControllerAs

我希望这可以帮助像我这样的人在这里结束搜索单元测试指令和调用它们的控制器,所有这些都使用ControllerAs语法。

谢谢你。

我会评论,但我不能。

答案 1 :(得分:0)

您的控制器位于:

element.scope().$$childTail.bugCtrl
相关问题