Javascript 如何使用Spy在JS函数执行时获取回调

Javascript 如何使用Spy在JS函数执行时获取回调,javascript,tdd,jasmine,sinon,spy,Javascript,Tdd,Jasmine,Sinon,Spy,我想监视一个函数,然后在函数完成/初始调用时执行回调 以下内容有点简单,但说明了我需要完成的工作: //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.callAfterExe

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

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

//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);
});
在西农有可能做到这一点吗?如果替代库解决了我的问题,也欢迎它们:)

您必须使用该函数。从文档中:

stub.callsArg(索引)

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


它很笨重,但你可以:

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