我想监视一个函数,然后在函数完成/初始调用时执行回调。
以下内容有点简单,但展示了我需要完成的任务:
//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);
});
在Sinon有可能吗?如果他们解决我的问题,替代图书馆也欢迎:)
答案 0 :(得分:4)
它很笨重,但你可以:
//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;
});
答案 1 :(得分:3)
你必须stub这个功能。来自文档:
stub.callsArg(index);
使存根调用该参数 提供索引作为回调函数。 stub.callsArg(0);引起了 stub将第一个参数称为回调。
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