2013-02-15 64 views
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'); 
       }; 
      }; 


      }); 

這是拋出一個錯誤類型錯誤:對象#有沒有方法「datePickerChange」

回答

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回購中看到的例子。 ngSwitch is a good example, 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); 
}); 
相關問題