MattDionis
MattDionis

Reputation: 3616

Is there a way to consolidate 'spyOn' setup in Jasmine test?

I'm doing some testing of Angular controllers with Jasmine and spying on almost a dozen methods. Is there any way to consolidate the spy setup? My current setup looks like:

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

This just strikes me as a lot of repeated code.

Upvotes: 2

Views: 87

Answers (2)

Jan
Jan

Reputation: 5825

Of course.

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

Upvotes: 1

Greg Burghardt
Greg Burghardt

Reputation: 18868

There is nothing in Jasmine that allows you to spy on methods in bulk. You could create your own. Something akin to:

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

You have two ways to call it. You can specify the object and methods explicitly:

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

Or spy on the whole object:

spyOnAll(playerService);

Upvotes: 1

Related Questions