Ability to spy on functions multiple times. #32

Closed
Ireney opened this Issue Nov 23, 2010 · 6 comments

5 participants

@Ireney

Right now, Jasmine does not allow me to set up multiple spies on the same function. For instance, given some constructor:

NavNet.Controller.LoginController = function LoginController (navNet) {
   this.loginService = navNet.getService("loginService");    
   this.storageService = navNet.getService("storageService");
};

My spy setup would looks something like this:

...

beforeEach(function() {
        framework = new NavNet();
        loginService = new NavNet.Services.LoginService();
        storageService = new NavNet.Services.StorageService();

        spyOn(framework, "getService").andReturn(loginService);
        spyOn(framework, "getService").andReturn(storageService);

        sut = new NavNet.Controllers.LoginController(framework);
    });

...

Maybe not the best example, as I actually inject the services I need, but it illustrates a point: the second spy on "getService" will fail as Jasmine will complain that "getService" is already being spied on. Fair enough. It would be nice if I was able to set up spies on multiple function calls, differentiated by parameters. Maybe something like:

spyOn(framework, "getService").with("loginService").andReturn(loginService);

Unless, of course, there is a way I am unaware of that will accomplish this >8)

@infews

You can do this by using .andCallFake, then switching on arguments and returning what you want.

@ragaskar

yep, you can use andCallFake here, although maybe we could add some extra helpers to help you set up fakes.

    framework = new NavNet();
    loginService = new NavNet.Services.LoginService();
    storageService = new NavNet.Services.StorageService();

    spyOn(framework, "getService").andCallFake(function(service) {
      if (service = "loginService") return loginService;
      if (service = "storageService") return storageService;
      return null;
    })
@Ireney

Ah ... good call ... thanks guys, I had just been learning to take advantage of .andCallFake for a number of my tests, but I have not thought of it in this scenario.

The helper method would certainly be nice, and/or more samples and scenarios for newbs such us me, if you have time >8)

Thanks again, I have been enjoying learning Jasmine ... great job!

@AlexCppns

@ragaskar I don't understand your example... how do I call andReturn twice with different values?

@slackersoft
Jasmine member

If you call the andReturn (or any of the others) function again on the existing spy, it will change the execution plan for the spy for all future calls.

@AlexCppns

@slackersoft Thanks, I just figured it out :).

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment