The Jasmine Spy Cheatsheet

Update: If you are using Jasmine 2.0 or above, the information here is out of date! Please go to instead.

Wanna be a spy fast? Well you are in luck!

Just kidding! This is actually a cheatsheet for Jasmine Spies.

See, while Jasmine itself is very intuitive to use, every time use spies I have to look up the docs. I would blame it on the poorly chosen method/property names, but I won't. Instead I finally wrote myself a cheatsheet. I hope it helps other folks too.

How to spy on a method?

spyOn(obj, 'method') // assumes obj.method is a function

How to verify it was called?


How to verify it was called with specific arguments?

expect(obj.method).toHaveBeenCalledWith('foo', 'bar')

How many times was it called?


What were the arguments to the last call?


How to reset all the calls made to the spy so far?


How to make a standalone spy function?

var dummy = jasmine.createSpy('dummy')

How to have spied method also calls through to the real function?

spyOn(obj, 'method').andCallThrough()

Update: if you are using Jasmine 2, andCallThrough() has been changed to and.callThrough().

How to get all arguments for all calls that have been made to the spy?

obj.method.argsForCall // this is an array

How do I fix the return value of a spy?

spyOn(obj, 'method').andReturn('Pow!')

Update: if you are using Jasmine 2, andReturn(value) has been changed to and.returnValue(value).

blog comments powered by Disqus