簡體   English   中英

我們如何在sinon js中存根並響應特定的函數調用

[英]How can we stub and respond to a particular function call in sinon js

假設我們有一個功能測試,它以不同的值被多次調用。 我們如何將其存入特定的參數值。 像下面

function test(key, cb) {
    // code
    cb();
}

test('one', function(arg){console.log(arg);});
test('two', function(arg){console.log(arg);});
test('three', function(arg){console.log(arg);});

我只想對它進行調用以“ two”調用,以驗證是否用“ two”調用過一次,並且還用arg執行回調以檢查函數調用后的狀態。

找不到任何api解決方案,因此使用了以下方法:

test = sinon.stub();

var calls = test.getCalls().filter(function(call) {
    return call.args[0] === 'two';
});

expect(calls.length).to.be.equal(1);
// to execute callback calls[0].args[0](arg1, arg2)

您可以使用sinon通過使用stub.withArgs()定位調用並讓其他人通過來完成所有這些操作。 例如:

const sinon = require('sinon')

let myObj = {
    write: function(str, cb){
        console.log("original function with: ", str)
        cb(str)
    }
}

// Catch only calls with 'two' argument
let stub = sinon.stub(myObj, 'write').withArgs("two")
stub.callsFake(arg => console.log("CALLED WITH STUB: ", arg))

// call the caught function's callback
stub.yields('two')

// let all others proceed normally
myObj.write.callThrough();

myObj.write("one", (str) => console.log("callback with: ", str))
myObj.write("two",  (str) => console.log("callback with: ", str))
myObj.write("three",  (str) => console.log("callback with: ", str))

// Make whatever assertions you want:
sinon.assert.calledOnce(stub) // passes

結果是:

original function with:  one  
callback with:  one  
callback with:  two  
CALLED WITH STUB:  two  
original function with:  three  
callback with:  three  

暫無
暫無

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

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