小编典典

如何使用Karma和Jasmine在角度服务中测试“私有”功能

angularjs

我的角度应用程序中有一个服务,看起来像这样:

angular.module('BracketService', []).factory('BracketService', [function() {
    function compareByWeight(a, b) {
        return a.weight - b.weight;
    }
    function filterWeightGroup(competitors, lowWeight, highWeight) {
        //filter stuff
    }
    function createBracketsByWeightGroup(weightGroup) {
        //create some brackets
    }
    //set some base line values
    var SUPER_HEAVY_WEIGHT = 500;
    var SUPER_LIGHT_WEIGHT = 20;
    return {
        //create brackets from a list of competitors
        returnBrackets: function(competitors) {
            var brackets = {};
            //get super light weights
            brackets.superLightWeights = createBracketsByWeightGroup(
                filterWeightGroup(competitors, 0, SUPER_LIGHT_WEIGHT)
                .sort(compareByWeight)
            );
            brackets.superHeavyWeights = createBracketsByWeightGroup(
                filterWeightGroup(competitors, SUPER_HEAVY_WEIGHT, Infinity)
                .sort(compareByWeight)
            );
            brackets.middleWeights = createBracketsByWeightGroup(
                filterWeightGroup(competitors, SUPER_LIGHT_WEIGHT, SUPER_HEAVY_WEIGHT)
                .sort(compareByWeight)
            );
            return brackets;
        }
    };

}]);

我不仅要对return语句中公开的功能/属性进行单元测试,还要对return语句之外的功能进行单元测试。

我的测试当前设置如下:

describe('BracketService', function() {
    beforeEach(module('bracketManager'));

    it('calling return brackets with no competitors will return 3 empty weight classes', inject(function(BracketService) {
        var mockCompetitors = [];
        var mockBracketResult = {superHeavyWeights: [[]], superLightWeights: [[]], middleWeights: [[]]};
        expect(BracketService.returnBrackets(mockCompetitors)).toEqual(mockBracketResult);
    }));
});

但是,如何测试return语句未公开的compare,filter和createBrackets函数?

谢谢!


阅读 215

收藏
2020-07-04

共1个答案

小编典典

无法测试这些功能。它们的范围是构成BracketService工厂的函数,在其他任何地方都不可见。如果要测试它们,则必须以某种方式公开它们。

您可以将它们移到它们自己的服务中(这似乎有些过头),也可以使用足够的数据组合对BracketService服务进行黑盒测试,以确保内部功能正常运行。那可能是最明智的方法。

如果您不想将它们放在单独的服务中,但仍然觉得需要测试这些内部功能,则只需将它们与returnBrackets一起从工厂退回即可。

当我有许多可以直接进行单独测试的帮助程序功能,但打开组合的Pandora盒进行黑盒测试时,可以这样做。我通常在这些函数前加上“
_”作为前缀,以表明它们是辅助函数,并且仅用于测试。

return {
    //create brackets from a list of competitors
    returnBrackets: function(competitors) {...},
    _filterWeightGroup: filterWeightGroup,
    _createBracketsByWeightGroup: createBracketsByWeightGroup
   };
2020-07-04