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

相关问题