0

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.

Rakesh Rawat
  • 327
  • 3
  • 14

2 Answers2

0

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)
Rakesh Rawat
  • 327
  • 3
  • 14
0

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  
Mark
  • 90,562
  • 7
  • 108
  • 148