5

I want to spy on a function, then execute a callback upon function completion/initial call.

The following is a bit simplistic, but shows what I need to accomplish:

//send a spy to report on the soviet.GoldenEye method function
var james_bond = sinon.spy(soviet, "GoldenEye");
//tell M about the superWeapon getting fired via satellite phone
james_bond.callAfterExecution({
    console.log("The function got called! Evacuate London!");
    console.log(test.args);
});

Is it possible to do this in Sinon? Alternate libraries welcome as well if they solve my problem :)

3.3volts
  • 178
  • 1
  • 6

2 Answers2

4

It's clunky but you can:

//send a spy to report on the soviet.GoldenEye method function
var originalGoldenEye = soviet.GoldenEye;

var james_bond = sinon.stub(soviet, "GoldenEye", function () {
  var result = originalGoldenEye.apply(soviet, arguments);

  //tell M about the superWeapon getting fired via satellite phone
  console.log("The function got called! Evacuate London!");
  console.log(arguments);
  return result;
});
David Braun
  • 5,573
  • 3
  • 36
  • 42
3

You have to stub the function. From the docs:

stub.callsArg(index);

Causes the stub to call the argument at the provided index as a callback function. stub.callsArg(0); causes the stub to call the first argument as a callback.

var a = {
  b: function (callback){
    callback();
    console.log('test')
  }
}

sinon.stub(a, 'b').callsArg(0)
var callback = sinon.spy()
a.b(callback)

expect(callback).toHaveBeenCalled()
//note that nothing was logged into the console, as the function was stubbed
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297