【问题标题】:How can I get the argument(s) of a stub in sinon and use one of the arguments + other data for the return value of a particular stub call如何在 sinon 中获取存根的参数并使用其中一个参数 + 其他数据作为特定存根调用的返回值
【发布时间】:2017-09-28 19:04:15
【问题描述】:

我想要实现的是将返回某个值的调用存根。该返回值由传递的参数之一和一个新值组成。

如何获取存根的参数并使用它为给定的存根调用形成返回值

例如

mockDb.query.onCall(0).return(
   Tuple(this.args(0), "Some other data");
);

我知道我可以做到:

sinon.stub(obj, "hello", function (a) {
    return a;
});

但是,这适用于整个存根,而不是单个存根调用。不幸的是,我无法为不同的调用提供不同的存根,因为我只有一个对象(db 存根)。

【问题讨论】:

    标签: node.js testing mocking sinon chai


    【解决方案1】:

    要在第一次调用存根时访问函数参数,您可以使用:

    sinon.stub(obj, "method").onCall(0).callsFake( function(arg) {
        return "data" + arg;
    });
    

    这将首先调用存根以返回与传递的参数连接的“数据”。

    我已经用 node v7.10 和 sinon v4 对其进行了测试。下面是整个测试脚本:

    const sinon = require('sinon');
    let obj = {
        test: (arg1, arg2) => {
            return arg1 + arg2;
        }
    }
    
    let stub = sinon.stub(obj, "test");
    stub.onCall(0).callsFake((arg1, arg2) => {
        return "STB" + arg1 + arg2;
    })
    
    
    console.log(stub("lol", "lol2")); // -> STBlollol2
    console.log(stub("lol", "lol3")); // -> undefined
    

    【讨论】:

    • 这似乎不起作用。我收到以下错误: ".callsFake is not a function" 。阅读规范,似乎 callFake 在整个存根上,而不是每个单独的调用。
    • 我扩展了我的答案以包括示例。可能我没有正确理解你的意思。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    相关资源
    最近更新 更多