有一个文件helperFunction.js,如下所示:
module.exports = (arg1, arg2) => {
\\function body
}
现在,在 file.js 中,可以通过以下方式简单地调用此函数:
let helperFunction = require('./helperFunction.js');
//some code here
let a=1, b=2;
let val = helperFunction(a,b);
//some code here
为了测试file.js,我想 stub helperFunction。但是,sinon.stub 的语法如下所示:
let functionStub = sinon.stub(file, "functionName");
在我的例子中,文件名本身就是函数名。现在如何为 helperFunction 创建 stub ?或者还有什么我可以做的吗?
最佳答案
您可以使用像 proxyquire 这样的库它可用于在测试期间覆盖依赖项。
这意味着你最终会得到这样的结果:
const helper = sinon.stub();
const moduleToTest = proxyquire('./your-file-name’, {
'./helperFunction': helper,
});
尽管如果您不想添加新库,您始终可以切换到重构 helperFunction.js
文件并将函数导出为命名导出而不是默认导出。这将为您提供一个具有您需要 stub 的方法的对象,并且该对象非常适合您当前的方法
关于javascript - 有什么方法可以 stub 这些类型的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61273518/