Search code examples
angularjsunit-testingkarma-jasmineangular-directiveangular-resource

Testing $resource.get params inside a directive link function


I am trying to test a $resources service call from the link function of a directive. My test is looking to see if the service is called with the correct parameter ($stateParams.id).

The Service:

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

The Directive:

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 });            
            });
    }
}}]);

The Specs:

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});
    });

When running this test I am getting the following error. Expected spy get to have been called with [ Object({ id: 'cd625c6e-944e-478e-b0f1-161c025d4e1a' }) ] but actual calls were [ Object({ id: undefined }) ].

So, here's my question, why the service is not called with $stateParams.id ?

Did I missed something on the Spy configuration ? Should I inject $statePArams differently ?


Solution

  • I think you have to inject your mock $stateParams object to your factory. Haven't tried this, but this could work in your spec

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

    This should inject your object with mock id when $stateParams is injected in the service