Chapter 6. Spies
As weâve learned, Jasmine will let us test if things are working the way we want them to. We want to ability to check if functions have been called, and whether or not theyâve been called how we want them to be called. We specify how our code should work.
In Jasmine, a spy does pretty much what its name implies: it lets you spy on pieces of your program (and in general, the pieces that arenât just variable checks). A little less exciting than James Bond, but still cool spying.
The Basics: Spying on a Function
Spying allows you to replace a part of your program with a spy. A spy can pretend to be a function or an object. When is this useful?
Letâs say that you have a class called Dictionary
. It represents an English dictionary, and can return âhelloâ and âworldâ:
var Dictionary = function() {}; Dictionary.prototype.hello = function() { return "hello"; }; Dictionary.prototype.world = function() { return "world"; };
And now letâs say that you have a class called Person
, which should be able to output âhello worldâ using Dictionary
(passed in as an argument). It might work like this:
var Person = function() {}; Person.prototype.sayHelloWorld = function(dict) { return dict.hello() + " " + dict.world(); };
So, to get your Person
to return âhello world,â youâd do something like this:
var dictionary = new Dictionary; var person = new Person; person.sayHelloWorld(dictionary); // returns "hello world"
You could, in theory, make the sayHelloWorld
function ...
Get JavaScript Testing with Jasmine now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.