The Jasmine Spy Cheatsheet

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?

expect(obj.method).toHaveBeenCalled()

How to verify it was called with specific arguments?

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

How many times was it called?

obj.method.callCount

What were the arguments to the last call?

obj.method.mostRecentCall.args

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

obj.method.reset()

How to make a standalone spy function?

var dummy = jasmine.createSpy('dummy')
$('button#mybutton').click(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).

Ever feel like you are wasting your life away debugging?
It doesn't have to be this way. Check out my debugging course.
blog comments powered by Disqus