使用Angular / Jasmine获取指令控制器的实例

时间:2016-10-27 21:50:44

标签: angularjs unit-testing angularjs-directive jasmine

当单元测试角度指令时,如何获取指令控制器的实例并在控制器上断言某些数据绑定?

function myDirective() {
  return {
    restrict: 'E',
    replace: true,
    templateUrl: 'tpl.html',
    scope: { },
    controller: function($scope) {
      $scope.text = 'Some text';
    }
  };
}

angular
  .module('example')
  .directive('myDirective', [
    myDirective
  ]);

单元测试

    describe('<my-directive>', function() {
      var element;
      var $compile;
      var $scope;

      beforeEach(module('example'));

      beforeEach(function() {
        inject(function(_$compile_, _$rootScope_) {
          $compile = _$compile_;
          $scope = _$rootScope_.$new();
        });
      });

      describe('basic functionality', function() {
        beforeEach(function() {
          element = $compile('<my-directive></my-directive')($scope);
          $scope.$digest();
        });

        it('should bind the correct text', function() {
          //?
        });
      });
    });

2 个答案:

答案 0 :(得分:0)

element = $compile('<my-directive></my-directive')($scope);
$scope.$digest();
ctrl = element.controller('myDirective');

答案 1 :(得分:0)

使用element.controller$scope联系element.controller($scope)。一些概念证明如下。

&#13;
&#13;
angular
  .module('example', [])
  .directive('myDirective', [
    function myDirective() {
      return {
        restrict: 'E',
        replace: true,
        //template: ['<div>{{ text }}</div>'].join(''),
        scope: {},
        controller: function($scope) {
          $scope.text = 'Some text';
        }
      };
    }
  ]);

describe('<my-directive>', function() {
  var element;
  var $compile;
  var $scope;

  beforeEach(module('example'));

  beforeEach(function() {
    inject(function(_$compile_, _$rootScope_) {
      $compile = _$compile_;
      $scope = _$rootScope_.$new();
    });
  });

  describe('basic functionality', function() {
    beforeEach(function() {
      element = $compile('<my-directive></my-directive')($scope);
      $scope.$digest();
    });

    it('should bind the correct text', function() {
      expect(element.controller($scope).scope().$$childTail.text).toEqual('Some text')
    });
  });
});
&#13;
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-mocks.js"></script>
&#13;
&#13;
&#13;