有没有办法对这些类型的函数进行存根?

问题描述 投票:0回答:1

有一个文件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

,我想存根helperFunction。但是,sinon.stub的语法如下:let functionStub = sinon.stub(file, "functionName");
在这里,我的文件名本身就是函数名。现在如何为

helperFunction

创建存根?还是我还能做些什么?
javascript node.js unit-testing sinon stub
1个回答
0
投票
您可以使用像proxyquire这样的库,可以在测试过程中覆盖依赖项。

这意味着您最终会得到类似这样的内容:

const helper = sinon.stub(); const moduleToTest = proxyquire('./your-file-name’, { './helperFunction': helper, });

尽管您不想添加新的库,但是您始终可以切换为重构helperFunction.js文件,并将函数作为命名导出而不是默认导出导出。这将为您提供一个对象,该对象具有您需要存根的方法,并且非常适合您当前的方法]
© www.soinside.com 2019 - 2024. All rights reserved.