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

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

本文关键字:location search 服务 何测试 测试      更新时间:2023-09-26

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

$location.path不改变url的'search'部分,它改变'path'部分并编码?字符。

应该避免前导为0的数字,因为它们在JS中可以被视为八进制。

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

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

您正在断言函数,而不是它的返回值。试一试:

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

你能试一下吗?您可以先执行函数,然后比较结果

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