So basically I have an function whose behavior I want to stub only if the argument is equal to something.
Example
var foo = {
bar: function(arg1){
return true;
}
};
var barStub = sinon.stub(foo, "bar");
barStub.withArgs("test").returns("Hi");
// Expectations
console.log(foo.bar("test")); //works great as it logs "Hi"
// my expectation is to call the original function in all cases except
// when the arg is "test"
console.log(foo.bar("woo")); //doesnt work as it logs undefined
I am having a hard time imagining when I would need such functionality.
Do you have a less synthetic example that might make me understand the need for this?
In my use case, i have one function which reads files. So I wanted to fake the response when it tries to read file xxxx.txt but for all the rest I want the function to behave as it is.
Now in Jasmine they have callThrough function which allows you to call the original function.
Same as https://github.com/cjohansen/Sinon.JS/issues/735
I guess we can close this as we know the answer.
I guess we can close this as we know the answer.
Yeah. From your use case it sounds like your function has more than one responsibility.
Even tough this issue is closed, I just want to post my case to prove it is necessary.
In my case, the program is run with babel-register and there is one unit test need to stub readFileSync for given filename and proxyquire to stub required module. However, babel-register would find .babelrc and parse it during execution. As a result, below code will fail.
stub(fs, 'readFileSync').withArgs(givenPath).returns(JSON.stringify(h3oConfig));
const foo = proxyquire('./foo', stub); // this will fail on reading .babelrc
It sounds that stub would better to have only customized returned value on given args.
@mocheng You can program the stub to have different behavior for different arguments like this:
stub(fs, 'readFileSync')
fs.readFileSync.withArgs(givenPath).returns(JSON.stringify(h3oConfig));
fs.readFileSync.withArgs('.babelrc').returns('#');
@mantoni Thanks.
It just looks tedious to mock .babelrc and my .babelrc has quite a lot of stuff.
Now, I just totally rely on proxyquire for this case.
@mocheng There is a new feature that just landed on master which allows to call through to the original implementation. It's not in a release yet, and it will only be supported in Sinon 2. You can point your dependency to master for now.
@mantoni cool. thanks!
Most helpful comment
@mocheng You can program the stub to have different behavior for different arguments like this: