如何在 AngularJS 指令中对控制器进行单元测试?

How can I unit test a controller in an AngularJS Directive?

我的指令是:

window.map.directive('dosingFrequencies', [
  function() {
    return {
      restrict: 'E',
      scope: true,
      templateUrl: '/views/directives/dosingFrequencies.html',
      controller: function($scope, util) {
console.log('here we go!');

        angular.extend($scope, {
          model: createModel(),

          addFrequency: function(med) {
            med.frequencies.push(createFreqModel());
          },

          removeFrequency: function(med, index) {
            med.frequencies.splice(index, 1);
          },

          showTimeChecked: function(freq) {
            if (freq.showTime) {
              freq.prn = false;
              freq.quantity = '';
              freq.quantityWhole = '';
              freq.quantityFrac = '';
              resetTimeToFirstLast(freq, this.model.facilityTimezone)
            }
            if (!freq.showTime) {
              for (var z = 0; z < freq.doses.length; z++) {
                freq.doses[z].quantity = '';
                freq.doses[z].quantityWhole = '';
                freq.doses[z].quantityFrac = '';
              }
              resetTimeToAllday(freq, this.model.facilityTimezone);
            }
          },

          updateDosingForm: function(med) {
            med.template.dosingForm = doseUnitChoices[med.med.dosingUnit] || ['', ''];
          }
        });

      }
    };
  }
]);

我的测试是:

fdescribe('MedPickerController', function() {
    var $scope;

    beforeEach(function() {
      module('mapApp');

      var html = '<dosing-frequencies></dosing-frequencies>';

      inject(function($compile, $injector) {
        var $controller, $rootScope, $httpBackend;
        $rootScope = $injector.get('$rootScope');
        $httpBackend = $injector.get('$httpBackend');

        $httpBackend.whenGET('/views/directives/dosingFrequencies.html').respond(200);

        $scope = $rootScope.$new();

        var elem = angular.element(html);
        var compiled = $compile(elem)($scope);

        var controller = elem.controller();

        $scope.$digest();

      });
    });

    it('should extend the scope', function() {
        expect($scope.model).not.toBeUndefined();
    });
});

但是,我的测试失败了。我的控制器中的 console.log 也没有执行。我做错了什么?

控制器自己制作。不要让它成为匿名函数。

所以

{
  // ... some directive options
  controller: function() {
    //  Your controller's logic
  }
}

做这样的事情。

{
// ... some directive options
  controller: "MedPickerController"
}

然后像定义任何其他控制器一样单独定义您的控制器。你甚至可以将它们放在同一个文件中,没关系。

那时候你只是在编写控制器测试。你不必担心它是一个指令。