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?
You can use spy.and.returnValues (as Jasmine 2.4).
for example
There is some thing you must be careful about, there is another function will similar spell
returnValue
withouts
, if you use that, jasmine will not warn you.For older versions of Jasmine, you can use
spy.andCallFake
for Jasmine 1.3 orspy.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.If you wish to write a spec for each call you can also use beforeAll instead of beforeEach :