有一个文件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
为了测试,我想存根helperFunction。但是,sinon.stub的语法如下:file.js
let functionStub = sinon.stub(file, "functionName");
在这里,我的文件名本身就是函数名。现在如何为创建存根?还是我还能做些什么?helperFunction
这意味着您最终会得到类似这样的内容:
const helper = sinon.stub();
const moduleToTest = proxyquire('./your-file-name’, {
'./helperFunction': helper,
});
尽管您不想添加新的库,但是您始终可以切换为重构helperFunction.js
文件,并将函数作为命名导出而不是默认导出导出。这将为您提供一个对象,该对象具有您需要存根的方法,并且非常适合您当前的方法]