如何使用间谍获得有关JS函数执行的回调

3.3*_*lts 5 javascript tdd spy jasmine sinon

我想监视一个函数,然后在函数完成/初始调用时执行回调。

以下内容有些简单,但显示了我需要完成的工作:

//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);
});
Run Code Online (Sandbox Code Playgroud)

在锡农有可能这样做吗?如果他们解决了我的问题,也欢迎备用库:)

And*_*rle 3

您必须存根该函数。来自文档:

stub.callsArg(index);

导致存根将提供的索引处的参数作为回调函数调用。存根.callsArg(0); 导致存根将第一个参数作为回调调用。

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
Run Code Online (Sandbox Code Playgroud)