簡體   English   中英

如何在后續調用 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();
  });

請注意,我需要它們是不同的函數,而不僅僅是不同的返回不同的值,因為我需要在第二個函數中調用 mocha 的 done(),因為它被異步調用。

您需要執行返回的函數:

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

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

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

您還可以使用(() => return 4)();將箭頭函數轉換為 IIFE (() => return 4)();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM