在指令 link 函数中测试 $resource.get 参数

Testing $resource.get params inside a directive link function

我正在尝试从指令的 link 函数测试 $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 调用服务?

我是否遗漏了有关 Spy 配置的内容?我应该以不同的方式注入 $statePArams 吗?

我认为你必须将你的模拟 $stateParams 对象注入你的工厂。没试过这个,但这在你的规范中可能有效

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

$stateParams 注入服务时,这应该用模拟 ID 注入您的对象