有没有办法巩固“spyOn'在Jasmine测试中设置?

时间:2015-07-06 17:59:47

标签: javascript angularjs unit-testing jasmine

我正在使用Jasmine对Angular控制器进行一些测试,并对近十二种方法进行间谍活动。有没有办法巩固间谍设置?我目前的设置如下:

spyOn(playersService, 'getInfo');
spyOn(playersService, 'getAccounts');
spyOn(playersService, 'getGames');
spyOn(playersService, 'getStatus');
spyOn(playersService, 'getEvents');
spyOn(viewersService, 'getViewers');
spyOn(helpersService, 'formatStats');
spyOn(helpersService, 'formatCounts');
spyOn(helpersService, 'formatValues');
spyOn(PlayerInfoController, 'slideToggle');
spyOn(PlayerInfoController, 'openModal');

这让我觉得很多重复的代码。

2 个答案:

答案 0 :(得分:1)

Jasmine中没有任何内容允许您批量监视方法。你可以创建自己的。类似于:

function spyOnAll(object) {
    var methods = Array.prototype.slice.call(arguments, 1);

    if (methods.length) {
        for (var i = 0; i < methods.length; i++) {
            spyOn(object, methods[i]);
        }
    }
    else {
        for (var key in object) {
            if (typeof object[key] === "function") {
                spyOn(object, key);
            }
        }
    }
}

您有两种方法可以调用它。您可以明确指定对象和方法:

spyOnAll(playerService, "getInfo",
                        "getAccounts",
                        "getGames",
                        "getStatus",
                        "getEvents",
                        "getViewers",
                        "formatStats",
                        "formatCounts",
                        "formatValues");

或者监视整个对象:

spyOnAll(playerService);

答案 1 :(得分:1)

当然。

function SpyOnInjected(service) {
  for (i in arguments) {
    spyOn(service, arguments[i]);
  }
}

SpyOnInjected(playersService, 'getInfo', 'getAccounts', 'getGames', 'getStatus', 'getEvents');
SpyOnInjected(viewersService, 'getViewers');
SpyOnInjected(helpersService, 'formatStats', 'formatCounts', 'formatValues');
SpyOnInjected(PlayerInfoController, 'slideToggle', 'openModal');