0

我的指令控制器中有一个函数,我正在尝试测试但找不到任何资源。我在每个之前

                   before each  {
                    scope = $rootScope ;
                    $compile(element)(scope);
                    scope.$digest();
                    }


          it('should update days when datepicker is changed', function () {
                scope.seldate = new Date('4/11/2014');
                scope.stdate = new Date('4/1/2014');
                scop`enter code here`e.days = 10;
                scope.$digest();
                scope.$apply(function() {
                    scope.seldate = new Date('4/12/2014');
                    scope.datePickerChange(); // This is a function in my directive controller
                });
                expect(scope.days).toBe(11);

            });

 app.directive('mydirective',function(){
      return {
              restrict:'E',
               scope:{
                days: '=',
                selectedDate: '=',
                startDate: '=' 

                 },
                $scope.datePickerChange = function () {
                    //Sod is helper for start of the day with hours/mins/seconds set to 0
                $scope.days = moment(new Date($scope.selectedDate)).sod().diff($scope.getStartDate(), 'days');
                };
             };


          });

这是抛出一个错误 TypeError: Object # has no method 'datePickerChange'

4

1 回答 1

1

您的指令声明无效:

app.directive('mydirective',function(){
      return {
              restrict:'E',
              scope:{
                days: '=',
                selectedDate: '=',
                startDate: '=' 
              },
              link: function(scope, elem, attrs) {
                scope.datePickerChange = function () {
                    //Sod is helper for start of the day with hours/mins/seconds set to 0
                    scope.days = moment(new Date($scope.selectedDate))
                                 .sod().diff($scope.getStartDate(), 'days');
                };
              }
      }
});

除此之外,为了测试你的指令,你应该遵循你可以在 Angular 的 github repo 中看到的例子。ngSwitch 是一个很好的例子,IMO

基本思想是你使用 $compile 来执行你的指令并检查它。

it('should do something', inject(function($rootScope, $compile) {
     var scope = $rootScope.$new();
     var element = $compile('<my-directive></my-directive>')(scope);

     //assert things.
     expect(scope.days).toEqual(somethingHere);
     scope.datePickerChange();
     expect(scope.days).toEqual(somethingElse);
});
于 2013-02-15T17:01:19.333 回答