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

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

本文关键字:函数 stub js sinon 调用      更新时间:2023-09-26

我试图写一个测试,我需要有一个函数存根与不同的函数取决于它是否第一次被调用或第二次。到目前为止,我已经试过了:

  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(),因为它是异步调用的。

您需要执行返回的函数:

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

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

将箭头函数转换为IIFE