簡體   English   中英

Sinon.js,只存根一次方法?

[英]Sinon.js, only stub a method once?

我想知道 sinon.js 是否有可能只存根一次方法?

例如:

sinon.stub(module, 'randomFunction', 'returnValue/function');

在我的測試中,這個module.randomFunction在同一個測試中被多次調用,但我只希望存根觸發一次然后恢復它,以便函數恢復其正常行為。

模擬真實代碼:

myModule.putItem(item, function (err, data) {
  if (err) {
    // do stuff
    return callback();
  } else {
    // do other stuff
    return callback(null, data);
  }
});

第一次我想觸發錯誤,其他時候我只想讓它繼續真正的流程。

這在sinon可以嗎?

親切的問候,

吉米

編輯:我根據@Grimurd 的回答發布了我為我的問題找到的解決方案

是的,這是可能的。 假設您使用 mocha 作為測試框架。

describe('some tests', function() {    
    afterEach(function() {
        sinon.restore();
    })

    it('is a test with a stub', function() {
        // This gets restored after each test.
        sinon.stub(module, 'randomFunction', 'returnValue/function');
    })
})

查看sinon 沙箱 api以獲取更多信息。

更新

要回答您的實際問題,

describe('some tests', function() {
    afterEach(function() {
        sinon.restore();
    })

    it('is a test with a stub', function() {
        // This gets restored after each test.
        sinon.stub(module, 'randomFunction')
            .onFirstCall().returns('foo')
            .onSecondCall().returns('bar')
            .onThirdCall().returns('foobar');
    })
})

記錄在http://sinonjs.org/docs/搜索 stub.onCall(n)

更新 2:由於 v5 sinon 現在默認創建沙箱,因此不再需要顯式創建沙箱。 有關詳細信息,請參閱從 v4 到 v5 的遷移指南

解決方法:

sandbox.stub(module, 'putItem')
  .onFirstCall().yields('ERROR')
  .onSecondCall().yields(null, item)

根據@grimurd 的回答,我設法讓它與“收益”一起工作。 Yields 觸發它在原始方法簽名中找到的第一個回調函數。

所以在第一次調用時我基本上說callback('error') ,在第二次調用時我說callback(null, item)

不知何故,我確實想知道回調是否是比 yields 更好的方法名稱;)

感謝您的回答!

其他答案似乎忽略了問題的關鍵部分:“我只希望存根觸發一次,然后將其恢復,以便函數恢復其正常行為”。

以下存根給定的方法一次,然后恢復到以前的行為:

let stub = sandbox.stub(module, 'method')
    .onFirstCall().returns(1)
    .onSecondCall().callsFake((...args) => {
        stub.restore();
        return module.method(...args);
    });

IMO達到了預期的行為簡單的方法。 從文檔:

stub.callThrough();
當沒有任何條件存根匹配時,導致調用包含在存根中的原始方法。

所以,一個真實的例子是:

let stub = sandbox.stub(module, 'method')
  .onSecondCall().returns('whatever');

stub.callThrough();

請注意,原始方法也將在一次被調用時執行。

暫無
暫無

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

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