仅对一个参数存根的函数

Stub a function for only one argument

所以基本上我有一个函数,只有当参数等于某个东西时我才想存根它的行为。 例子

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

我正在使用这个包https://www.npmjs.com/package/sinon

环顾四周:

https://github.com/cjohansen/Sinon.JS/issues/735 https://groups.google.com/forum/#!topic/sinonjs/ZM7vw5aYeSM

根据第二个 link,克里斯蒂安写道:

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

我倾向于尝试选项 3 - 看看你是否可以让它工作(不幸的是文档真的很简单)。

我遇到了同样的问题。接受的答案已过时。

stub.callThrough(); 将实现此目标。

只需在 barStub.withArgs("test").returns("Hi")

之后调用 barStub.callThrough()

https://sinonjs.org/releases/v7.5.0/stubs/