【问题标题】:How to stub with a different function on subsequent calls to sinon.js stub如何在对 sinon.js 存根的后续调用中使用不同的函数存根
【发布时间】:2016-09-20 13:58:35
【问题描述】:

我正在尝试编写一个测试,我需要根据是第一次调用还是第二次调用不同的函数来存根函数。到目前为止,我已经尝试过:

  this.dispatcherStub = sinon.stub(alt.dispatcher, 'dispatch');

  this.dispatcherStub.onFirstCall().returns((dataArgs) => {
    // Some assertion on the data
  });

  this.dispatcherStub.onSecondCall().returns((dataArgs) => {
    // Another assertion on the data
    done();
  });

请注意,我需要它们是不同的函数,而不仅仅是返回不同的值,因为我需要在第二个函数中调用 mocha 的 done(),因为它是异步调用的。

【问题讨论】:

    标签: javascript mocha.js sinon


    【解决方案1】:

    您需要执行返回的函数:

    this.dispatcherStub = sinon.stub(alt.dispatcher, 'dispatch');
    
      this.dispatcherStub.onFirstCall().returns(
          (function () {}();
      });
    
      this.dispatcherStub.onSecondCall().returns((dataArgs) => {  
        (function () {
            done();
        }();
      });
    

    您还可以使用 (() => return 4)(); 将箭头函数转换为 IIFE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-02
      • 2018-03-06
      • 2015-07-01
      • 2020-07-01
      • 2016-08-16
      • 2016-10-03
      • 2017-07-12
      相关资源
      最近更新 更多