简体   繁体   中英

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

Suppose we have a function test, that has been called multiple times with different values. How can we stub it for a particular parameter value. Like in the following

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

I want to stub it for the call with 'two' only to verify if it is called once with 'two' and also execute callback with arg to check the state after function call.

Didn't find any api solution so used the following approach:

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)

You can do this all with sinon by targeting the call with stub.withArgs() and letting the others pass through. For example:

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

This results in:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM