O'Reilly logo

JavaScript Testing with Jasmine by Evan Hahn

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required