【问题标题】:Howto get a callback on JS function execution using a Spy如何使用 Spy 在 JS 函数执行中获取回调
【发布时间】:2013-03-15 17:27:53
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: javascript tdd jasmine sinon spy


    【解决方案1】:

    它很笨重,但你可以:

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

    【讨论】:

      【解决方案2】:

      你必须stub这个函数。来自文档:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-18
        • 1970-01-01
        • 1970-01-01
        • 2012-08-12
        • 2012-08-16
        相关资源
        最近更新 更多