5

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

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

//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);
});

在诗乃可以做到这一点吗?如果他们解决了我的问题,也欢迎备用库:)

4

2 回答 2

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;
});
于 2014-01-31T21:51:06.880 回答
3

你必须存根函数。从文档:

stub.callsArg(index);

使存根将提供的索引处的参数作为回调函数调用。stub.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
于 2013-03-26T06:22:18.230 回答