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 return the string literal ...
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.