Testing an AngularJS service that uses the $ routeParams parameter as a URL parameter

I use Jasmine to test my services. One of my services uses the $ routeParams parameter as the URL parameter. Now when I test, $ routeParams becomes undefined

this is my utility code

    this.getProjectFunction = function (options) {
                $http.get(rootUrl + $routeParams.projectName)
                        .success(options.success)
                        .error(options.error);
            };

And this is how my test looks like

describe('App Service', function() {

    describe('App Service Tests', function(){

        var httpBackend, service, optionsSpy, routeParams;

        var returnData = [{"id":1,"name":"test"];

        beforeEach( module( 'appName' ) );

        beforeEach(
            inject(
                function($httpBackend,projectService,routeParams) {
                    service = projectService;
                    optionsSpy = jasmine.createSpyObj('optionsSpy',['success','error','data']);
                    routeParams = $routeParams;
                    httpBackend = $httpBackend;

                }
            )
        );

         afterEach(function() {
           httpBackend.verifyNoOutstandingExpectation();
           httpBackend.verifyNoOutstandingRequest();
        });


            //this should get a specific project
            it('should call the getAllProjectsFunction function that will return an argument array',

                           function(){

                               //set up some data for the http call to return and test later.
                               httpBackend.whenGET('../'+routeParams.projectName).respond(returnData);
                               service.getProjectFunction(optionsSpy);

                               httpBackend.flush();                            
                               expect(optionsSpy.success.mostRecentCall.args[0]).toBe(returnData);
                           }
            );
    });
});

Im a new jasmine test. Thanks for the help, you have a nice day :)

+3
source share
1 answer

You need to enter $routeParamsnot routeParams, and then you can install routeParams.projectName = 'foo';and then install httpBackend.whenGET('../foo').respond(returnData);(it ../foomight be more like /foosince I don’t think that “one folder” works here.)

+3
source

All Articles