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

时间:2015-06-12 19:27:45

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

我的指示是:<​​/ p>

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也不会执行。我做错了什么?

1 个答案:

答案 0 :(得分:1)

自行制作控制器。不要把它变成匿名函数。

所以而不是

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

做这样的事情。

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

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

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