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 :)
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;
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With