admin管理员组

文章数量:1388072

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

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./package/sinon

Share Improve this question edited Jul 22, 2015 at 22:47 Gepser Hoil 4,2465 gold badges25 silver badges36 bronze badges asked Jul 22, 2015 at 22:35 GyandeepGyandeep 13.6k5 gold badges32 silver badges42 bronze badges 1
  • Where do you define sinon? – nril Commented Jul 22, 2015 at 22:41
Add a ment  | 

2 Answers 2

Reset to default 8

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/releases/v7.5.0/stubs/

Looking around:

https://github./cjohansen/Sinon.JS/issues/735 https://groups.google./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).

本文标签: javascriptStub a function for only one argumentStack Overflow