Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto get a callback on JS function execution using a Spy

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 :)

like image 536
3.3volts Avatar asked Mar 26 '13 02:03

3.3volts


2 Answers

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;
});
like image 99
David Braun Avatar answered Nov 14 '22 22:11

David Braun


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
like image 40
Andreas Köberle Avatar answered Nov 14 '22 21:11

Andreas Köberle