R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

Spy

Problem

Implement a spyOn function that does the following:

- Takes a function as its parameter

- Returns a spy function that takes any number of parameters

- spy calls func with the given arguments and returns what func returns

- spy has the following methods :

- .getCallCount( ) : returns the number of times spy has been called  

- .wasCalledWith(val) : returns true if spy was ever called with val, else returns false

- .returned(val) : returns true if spy ever returned val, else returns false

Example

    function add(a, b) { return a + b; }
    
    var addSpy = spyOn( add );
    
    addSpy.getCallCount(); // 0
    
    addSpy(2, 4); // returns 6
    addSpy.getCallCount(); // 1
    
    addSpy(3, 5); // returns 8
    addSpy.getCallCount(); // 2
    addSpy.wasCalledWith(2); // true
    addSpy.wasCalledWith(0); // false
    addSpy.returned(6); // true
    addSpy.returned(9); // false

Solution 

    var spyOn = function (func) {

      var callCount = 0,
          callVals  = [],
          retVals   = [];

      var spy = function () {
        var args = [].slice.call(arguments);
        var retVal = func.apply(this, args);
        retVals.push(retVal);
        callVals = callVals.concat(args);
        callCount++;
        return retVal;
      };

      spy.getCallCount = function () { 
            return callCount; 
        };
      spy.wasCalledWith = function (val) { 
            return (callVals.indexOf(val) > -1); 
        };
      spy.returned = function (val) { 
            return (retVals.indexOf(val) > -1); 
        };

      return spy;
    };

The End

Spy

By Ivan Loughman-Pawelko

Spy

Technical interview problem on spies

  • 1,398