Oam Psy
Oam Psy

Reputation: 8663

How to test $location and .search() in a service

I have a simple service that has a number of methods to retrieve various values from a URL:

app.service('urlInterpSrv', function($location) {
    return {
        getCartID : function() {
            return $location.search().getCartID;
        },
        getUserAddress : function() {
            return $location.search().getUserAddress;
        },
        getShippingCountry : function() {
            return $location.search().getShippingCountry;
        },
        getCookie : function() {
            return $location.search().getCookie;
        },
        getUsername : function() {
            return $location.search().getUsername;
        }
    };
});

I call these in my controllers simply via:

app.controller('ShoppingCartController', function($scope, urlInterpSrv, $rootScope) {

    $scope.getCartID = urlInterpSrv.getCartID();
    $scope.getShippingCountry = urlInterpSrv.getShippingCountry();

});

Three questions? Should i be testing the service explicitly, or the controller, or both?

I have tried testing the service explicitly via:

describe('urlInterpSrv', function(){

    var $location;

    beforeEach(module('myApp'));

    beforeEach(inject(function (_urlInterpSrv_, _$location_) {
        this.urlInterpSrv = _urlInterpSrv_;
        $location = _$location_;
    }));


    it('should getCartID from url', function(){
        $location.path('/?getCartID=0087598');
        expect(this.urlInterpSrv.getCartID).toEqual(0087598);
    });

});

However i get the error:

Expected Function to equal 87598.

Upvotes: 1

Views: 464

Answers (3)

Estus Flask
Estus Flask

Reputation: 223104

$location.path doesn't change 'search' part of url, it changes 'path' part and encodes ? character instead.

Numbers with leading zero should be avoided because they can be treated as octals in JS.

It isn't $location's job to parse primitives in parameter values, getCartID equals to '0087598' string, not to 87598.

it('should getCartID from url', function(){
    $location.url('/?getCartID=0087598');
    expect(this.urlInterpSrv.getCartID()).toEqual('0087598');
});

Upvotes: 3

Hrishi
Hrishi

Reputation: 761

coould you try below.. you can execute the function first and then compare the results

it('should getCartID from url', function(){
    $location.path('/?getCartID=0087598');
    var cartId = this.urlInterpSrv.getCartID();
    expect(cartId).toEqual(0087598);
});

Upvotes: 0

Alexandr Lazarev
Alexandr Lazarev

Reputation: 12892

You are asserting function, not its returned value. Try:

expect(this.urlInterpSrv.getCartID()).toEqual(0087598);

Upvotes: 1

Related Questions