So basically I have an function whose behavior I want to stub only if the argument is equal to something. Example
var sinon = require('sinon');
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 using this package https://www.npmjs.com/package/sinon
I had the same problem. The accepted answer is outdated.
stub.callThrough();
will acheive this.
just call barStub.callThrough()
after barStub.withArgs("test").returns("Hi")
https://sinonjs.org/releases/v7.5.0/stubs/
Looking around:
https://github.com/cjohansen/Sinon.JS/issues/735 https://groups.google.com/forum/#!topic/sinonjs/ZM7vw5aYeSM
According to the second link, Christian writes:
Not possible, and should mostly not be necessary either. Your options are:
- Simplifying your tests to not cover so many uses in one go
- Express the desired behavior in terms of withArgs, returns/yields etc
- Use
sinon.stub(obj, meth, fn)
to provide a custom function
I'd be inclined to try out option 3 - see if you can get it to work (the documentation is really light unfortunately).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With