Let’s say we have a function with two arguments. It’s being called many times with different arguments on every call. So, its impossible to stub it with withArgs option.
async function foo(args1, args2){ // some business logic return result }
I want to write a stub function which will check the actual arguments being passed (args1, args2) and return a static response with a switch case. Something on the following lines:
sinon.stub(TestModule, "foo") .resolves(asyn function(args1, args2){ switch(args2){ case "a": return 1 case "b": return 2 case "c": return 3 default: return 0 } })
So, how to return based on actual arguments?
Advertisement
Answer
You can use stub(obj, 'meth').callsFake(fn)
to dynamically check what passed in and response to it.
An example would be:
const mockFunction = (arg1, arg2) => { switch(arg2) {case "a": return 1 ...}} sinon.stub(TestModule, "foo").callsFake(mockFunction);
Note that for an earlier version of Sinon < 3.0.0
You should use var stub = sinon.stub(object, "method", fn);
instead.