trysis
trysis

Reputation: 8416

Return Certain Value Only With Certain Parameters

In Jasmine, is there any way to return a certain value from a spy only if it was called with certain parameters? For example, can I have something like:

describe('my test', function() {
  beforeEach(function() {
    this.mySpy = jasmine.createSpy();

    // not sure how to do this, so this is pseudocode
    this.mySpy.and.returnValue(true).when.calledWith(false);
    this.mySpy.and.returnValue(false).when.calledWith(true);
  });

  it('returns true if called with false', function() {
    expect(this.mySpy(false)).toEqual(true);
  });

  it('returns false if called with true', function() {
    expect(this.mySpy(true)).toEqual(false);
  });
});

I looked through the docs, but couldn't quite find what I wanted, and couldn't find anything related by searching. I can see why there wouldn't be a case for this - you know what you are calling, and when, and why, and with what parameters, so why make anything more specific? At the same time, this could result in more code, when you could specify exactly what you want to return once, and not have to specify it again.

Upvotes: 1

Views: 300

Answers (1)

Carlos Pinto
Carlos Pinto

Reputation: 558

I ran into this same problem today. The way I fixed it was by calling a fake method instead of the "someMethod" and handling the params to return the desired return value:

spyOn(SomeObj, "someMethod").and.callFake(function (property ) {
                        if (property === "someValue") {
                            return "someReturnValue";
                        } else if (property === "someOtherValue") {
                            return "someOtherReturnValue";
                        }
                    });

Upvotes: 1

Related Questions