javascript - 只为一个参数 stub 函数

标签 javascript node.js mocking sinon

所以基本上我有一个函数,只有当参数等于某个值时,我才想对其行为进行 stub 。
例子

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

最佳答案

我有同样的问题。接受的答案已过时。
stub.callThrough();将实现这一点。

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

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

关于javascript - 只为一个参数 stub 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31575215/

相关文章:

python - 如何模拟不在测试范围内的方法?

node.js - 如何模拟来自 http.request 的响应(nodejs、jasmine、sinon)

Javascript Obfuscator 在本地运行,每次编译

node.js - 如何从 node.js 应用程序获取 docker 映射端口?

javascript - 如何使用 mocha/chai 模拟窗口/文档

javascript - 加密 JS : TripleDES not encrypting properly

java - Mockito 方法调用链

javascript - Google 如何屏蔽搜索结果页面上链接的真实 URL?

javascript - Ember.js 重写的 Controller 没有引用原始模型?

javascript - 带有可包装的标签+字段单元的表单,但在包装时可以很好地排列