Friday, May 17, 2024
64
rated 0 times [  65] [ 1]  / answers: 1 / hits: 85970  / 10 Years ago, wed, november 12, 2014, 12:00:00

Say I'm spying on a method like this:



spyOn(util, foo).andReturn(true);


The function under test calls util.foo multiple times.



Is it possible to have the spy return true the first time it's called, but return false the second time? Or is there a different way to go about this?


More From » unit-testing

 Answers
20

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.


[#68826] Monday, November 10, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaleefridad

Total Points: 399
Total Questions: 97
Total Answers: 114

Location: North Korea
Member since Fri, Nov 4, 2022
2 Years ago
;