如何在后续调用 sinon.js 存根时使用不同的函数存根

How to stub with a different function on subsequent calls to sinon.js stub

我正在尝试编写一个测试,其中我需要使用不同的函数存根的函数,具体取决于它是第一次调用还是第二次调用。到目前为止我已经尝试过:

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

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

您需要执行返回的函数:

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

  this.dispatcherStub.onFirstCall().returns(
      (function () {}();
  });

  this.dispatcherStub.onSecondCall().returns((dataArgs) => {  
    (function () {
        done();
    }();
  });

您还可以使用 (() => return 4)();

将箭头函数转换为 IIFE