I want to spy on a function, then execute a callback upon function pletion/initial call.
The following is a bit simplistic, but shows what I need to acplish:
//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 wele as well if they solve my problem :)
I want to spy on a function, then execute a callback upon function pletion/initial call.
The following is a bit simplistic, but shows what I need to acplish:
//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 wele as well if they solve my problem :)
Share Improve this question edited Mar 26, 2013 at 2:36 3.3volts asked Mar 26, 2013 at 2:24 3.3volts3.3volts 1881 silver badge6 bronze badges2 Answers
Reset to default 4It'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;
});
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