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.
JavaScript
x
5
1
async function foo(args1, args2){
2
// some business logic
3
return result
4
}
5
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:
JavaScript
1
15
15
1
sinon.stub(TestModule, "foo")
2
.resolves(asyn function(args1, args2){
3
switch(args2){
4
case "a":
5
return 1
6
case "b":
7
return 2
8
case "c":
9
return 3
10
default:
11
return 0
12
}
13
14
})
15
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:
JavaScript
1
3
1
const mockFunction = (arg1, arg2) => { switch(arg2) {case "a": return 1 }}
2
sinon.stub(TestModule, "foo").callsFake(mockFunction);
3
Note that for an earlier version of Sinon < 3.0.0
You should use var stub = sinon.stub(object, "method", fn);
instead.