If you’re tired of Googling for the Jasmine docs every time you need to use a spy, look no further!
Jasmine is my testing framework of choice when I’m writing Angular. And I was just getting used to all those spy
methods with the help of Toby Ho’s cheat sheet, and then Jasmine 2 came along and changed all the method names.
So here’s an updated cheat sheet for spying with Jasmine 2.
Create a spy
Spy on an existing method
Create a new function to use as a spy
Create a new object with spy functions as properties
Modify behavior when the spy is called
Default spy behavior is to record the call with its context/arguments and stop there. Spies will not call through to the spied function by default. These calls all modify that behavior.
Call through to the original
obj.method.and.callThrough();
Return the specified value
obj.method.and.returnValue(val);
Call the given function instead of the real one
obj.method.and.callFake(function() {...});
Throw an error
obj.method.and.throwError(err);
Reset to default stubbing behavior (resets the operations above)
obj.method.and.stub();
Verifying and counting calls on a spy
Every call to a spy is exposed on the calls
property
Returns true
if any calls have been made
obj.method.calls.any();
Returns the number of times the spy got called
obj.method.calls.count();
Reset the call tracker
obj.method.calls.reset();
After calling reset()
, any()
will be false
, count()
will be 0
, etc.
Returns the first call’s context and arguments
obj.method.calls.first();
It will return an object like this:
Returns the most recent call’s context and arguments
obj.method.calls.mostRecent();
It will return an object like this:
Returns array of context and arguments passed to each call
obj.method.calls.all();
The returned array looks like this:
That’s it! Go test some stuff.