Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have different return values for multiple calls on a Jasmine spy

People also ask

What is spyOn in Jasmine?

spyOn() spyOn() is inbuilt into the Jasmine library which allows you to spy on a definite piece of code.

How do you spyOn a method in Jasmine?

There are two ways to create a spy in Jasmine: spyOn() can only be used when the method already exists on the object, whereas jasmine. createSpy() will return a brand new function: //spyOn(object, methodName) where object. method() is a function spyOn(obj, 'myMethod') //jasmine.

How do you parameter a function as a spy?

spyOn() takes two parameters: the first parameter is the name of the object and the second parameter is the name of the method to be spied upon. It replaces the spied method with a stub, and does not actually execute the real method. The spyOn() function can however be called only on existing methods.

What is Jasmine createSpy?

jasmine. createSpyObj is used to create a mock that will spy on one or more methods. It returns an object that has a property for each string that is a spy. If you want to create a mock you should use jasmine. createSpyObj .


You can use spy.and.returnValues (as Jasmine 2.4).

for example

describe("A spy, when configured to fake a series of return values", function() {
  beforeEach(function() {
    spyOn(util, "foo").and.returnValues(true, false);
  });

  it("when called multiple times returns the requested values in order", function() {
    expect(util.foo()).toBeTruthy();
    expect(util.foo()).toBeFalsy();
    expect(util.foo()).toBeUndefined();
  });
});

There is some thing you must be careful about, there is another function will similar spell returnValue without s, if you use that, jasmine will not warn you.


For older versions of Jasmine, you can use spy.andCallFake for Jasmine 1.3 or spy.and.callFake for Jasmine 2.0, and you'll have to keep track of the 'called' state, either through a simple closure, or object property, etc.

var alreadyCalled = false;
spyOn(util, "foo").andCallFake(function() {
    if (alreadyCalled) return false;
    alreadyCalled = true;
    return true;
});