Jasmine 2 Spy Cheat Sheet

By Dave Ceddia

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
spyOn(obj, 'method');   // same as Jasmine 1
Create a new function to use as a spy
jasmine.createSpy('optional name');    // same as Jasmine 1
Create a new object with spy functions as properties
jasmine.createSpyObj('name', ['fn1', 'fn2', ...]);    // same as Jasmine 1

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:

{
  object: {...},  // 'this' object
  args: []        // array of arguments
}
Returns the most recent call’s context and arguments
obj.method.calls.mostRecent();

It will return an object like this:

{
  object: {...},  // 'this' object
  args: []        // array of arguments
}
Returns array of context and arguments passed to each call
obj.method.calls.all();

The returned array looks like this:

[
  {
    object: {...},  // 'this' object
    args: [...]     // array of arguments
  },  
  ...               // one object for each call
]

That’s it! Go test some stuff.