【问题标题】:Stub a function for only one argument只为一个参数存根函数
【发布时间】:2015-07-22 22:35:28
【问题描述】:

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

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

【问题讨论】:

  • 你在哪里定义sinon?

标签: javascript node.js mocking sinon


【解决方案1】:

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

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

只需在barStub.withArgs("test").returns("Hi") 之后调用barStub.callThrough()

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

【讨论】:

    【解决方案2】:

    环顾四周:

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

    根据第二个链接,Christian 写道:

    不可能,而且大多数情况下也没有必要。您的选择 是:

    1. 简化您的测试,一次性涵盖这么多用途
    2. 用 withArgs、returns/yields 等表达所需的行为
    3. 使用sinon.stub(obj, meth, fn) 提供自定义函数

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-29
      • 2019-01-05
      • 2019-10-19
      • 2018-01-27
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      相关资源
      最近更新 更多