Test spies

A spy is an approach that wraps all the methods of an object and records the inputs and outputs from that method as well as the number of calls. By wrapping the calls, it is possible to examine exactly what was passed in and what came out of the function. Test spies can be used when the exact inputs into a function are not known beforehand.

In other languages, building test spies requires reflection and can be quite complicated. We can actually get away with making a basic test spy in no more than a couple of lines of code. Let's experiment.

To start we'll need a class to intercept:

var SpyUpon = (function () {
  function SpyUpon() {
  }
  SpyUpon.prototype.write = function (toWrite) {
    console.log(toWrite);
  };
  return SpyUpon;
})();

Now we would like to spy on this function. Because functions are first class objects in JavaScript we can simply rejigger the SpyUpon object:

var spyUpon = new SpyUpon();
spyUpon._write = spyUpon.write;
spyUpon.write = function (arg1) {
  console.log("intercepted");
  this.called = true;
  this.args = arguments;
  this.result = this._write(arg1, arg2, arg3, arg4, arg5);
  return this.result;
};

Here we take the existing function and give it a new name. Then we create a new function that calls the renamed function and also records some things. After the function has been called we can examine the various properties:

console.log(spyUpon.write("hello world"));
console.log(spyUpon.called);
console.log(spyUpon.args);
console.log(spyUpon.result);

Running this code in node gets us the following:

hello world
7
true
{ '0': 'hello world' }
7

Using this technique, it is possible to get all sorts of insight into how a function is used. There are a number of libraries that support creating test spies in a more robust way than our simple version here. Some provide tools for recording exceptions, the number of times called, and the arguments for each call.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset