Temporarily Replace

Some languages provide another way to test what code does without invoking the things that it calls. In the previous section, we showed a technique for locally redefining a function for the duration of the block, but the method will be redefined for all instances created from the module around the redefined function if you are using modules in an object-oriented way.

In contrast, JavaScript, with its dynamic characteristics and prototypal inheritance, allows each instance of an object to be independently customized. You can create an instance of an object and replace the implementation of its methods without modifying the behavior of the methods in any other instance (Listing 6-10).

Listing 6-10: Simple example of replacing the toString() method of a JavaScript object

var testObject = new Number();
testObject.toString = function() {
  return "I'm a test object.";
};

This technique can be quite powerful. The Jasmine test framework4 has a spyOn() method that is used to capture and verify that a method was called, the number of calls, and the arguments for each call as shown in Listing 6-11. The spyOn() method wraps the original method in a Spy object that intercepts the call and records the characteristics of the calls before optionally calling the original method. The teardown automatically reverts the method to the original implementation.

4. http://pivotal.github.com/jasmine/

Listing 6-11: The Jasmine spyOn() method uses object redefinition to insert a recording proxy between the caller and the callee

describe('Spy example', function() {
  it('calls toString', function() {
    var testObject = new Number();
    spyOn(testObject, 'toString'),

    var result = testObject.toString();

    expect(testObject.toString).toHaveBeenCalled();
  });
});

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

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