【问题标题】:Is there any way to stub these type of functions?有没有办法存根这些类型的函数?
【发布时间】:2020-07-31 01:35:50
【问题描述】:

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

    您可以使用像 proxyquire 这样的库,它可用于在测试期间覆盖依赖项。

    这意味着你最终会得到这样的结果:

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

    虽然您不想添加新库,但您始终可以切换到重构 helperFunction.js 文件并将您的函数导出为命名导出而不是默认导出。这将为您提供一个对象,该对象具有您需要存根的方法,并且非常适合您当前的方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      相关资源
      最近更新 更多