0

我試圖從一個指令的鏈接函數測試$ resources服務調用。我的測試正在查看是否使用正確的參數($ stateParams.id)調用該服務。

的服務:

AppServices.factory('lastReportService', ['$resource',function($resource){    
    return $resource('/endpoint/:id/report/',null, { id : '@id'}) 
}]); 

的指令:

AppDirectives.directive('directive', ['lastReportService','$stateParams', function(lastReportService,$stateParams) { 
    return { 
     restrict: 'E', 
     templateUrl:'/static/views/directives/directive.html', 
     scope:{ 
      object : '=', 
     }, 
     link: function(scope, element, attrs) { 
      lastReportService.get({id:$stateParams.id}, 
       function(response){ //DO STUFF WITH RESPONSE });    
      }); 
    } 
}}]); 

規格:

beforeEach(function() { 
    inject(function ($compile, $rootScope, _$q_, lastReportService) { 
     compile = $compile; 
     scope = $rootScope.$new() 
     object = {"id":"cd625c6e-944e-478e-b0f1-161c025d4e1a"}; 
     $stateParams = {"id":"cd625c6e-944e-478e-b0f1-161c025d4e1a"}; 
     $serviceForlastReportService = lastReportService; 

     //Service Spy 
     var lastReportGetDeferred = _$q_.defer(); 
     spyOn($serviceForlastReportService, 'get').and.callFake(function(){ 
      lastReportGetDeferred.promise.then(this.get.arguments[1]); 
      return {$promise: lastReportGetDeferred.promise}; 
     }); 

     lastReportGetDeferred.resolve({report:'data'}); 
     adGroupTopNav = compile(angular.element('<directive object="object"></directive>'))(scope); 

     scope.$digest(); 
     }); 
}); 
    it('should fetch last report service api to retrieve the last report information', function(){ 
     expect($serviceForlastReportService.get).toHaveBeenCalledWith({id:$stateParams.id}); 
    }); 

運行時這個測試我得到以下錯誤。 Expected spy get to have been called with [ Object({ id: 'cd625c6e-944e-478e-b0f1-161c025d4e1a' }) ] but actual calls were [ Object({ id: undefined }) ].

所以,這是我的問題,爲什麼不用$ stateParams.id調用服務?

我錯過了什麼間諜配置?我應該以不同的方式注入$ statePArams嗎?

回答

0

我認爲你必須注入你的模擬$stateParams對象到你的工廠。沒有試過,但是這可能在你規範

$provide.value('$stateParams',object); 

工作,這應該與模擬ID注入你的對象時$stateParams在服務注入

+0

這工作,非常感謝! – Sylvestre

相關問題