如何在服务中测试$ location和.search()

时间:2015-09-23 10:34:59

标签: javascript angularjs jasmine karma-jasmine jasmine-jquery

我有一个简单的服务,它有许多方法可以从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;
        }
    };
});

我只是通过以下方式在控制器中调用它们:

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

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

});

三个问题?我应该明确地测试服务,还是控制器,或两者兼而有之?

我已尝试通过以下方式明确测试服务:

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

});

然而我收到错误:

Expected Function to equal 87598.

3 个答案:

答案 0 :(得分:3)

$location.path doesn't change 'search' part of url,它会更改“路径”部分并改为编码?字符。

应避免使用前导零的数字,因为它们可以是JS中的treated as octals

在参数值中解析基元不是$location的工作,getCartID等于'0087598'字符串,而不是87598。

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

答案 1 :(得分:1)

您正在断言函数,而不是其返回值。尝试:

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

答案 2 :(得分:0)

你可以尝试下面..你可以先执行该功能,然后比较结果

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