Gyandeep
Gyandeep

Reputation: 13578

Stub a function for only one argument

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

Upvotes: 4

Views: 2353

Answers (2)

Dan
Dan

Reputation: 391

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/

Upvotes: 8

brandonscript
brandonscript

Reputation: 73034

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:

  1. Simplifying your tests to not cover so many uses in one go
  2. Express the desired behavior in terms of withArgs, returns/yields etc
  3. 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).

Upvotes: 1

Related Questions