javascript - 有什么方法可以 stub 这些类型的函数吗?

标签 javascript node.js unit-testing sinon stub

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

相关文章:

javascript - Jquery 函数在 Internet Explorer 中只能运行一半

javascript - 如何使函数 add 在 javascript 中工作 - console.log(add(2)(3)(4))//9 而不使用 valueof 或 toString

javascript - 使用 karma-browserify 对 AngularJS 应用程序进行单元测试

unit-testing - 测试不编译 : "the async keyword is missing from the function declaration"

node.js - Babel 可以针对 "node --harmony"而不是 ES5 进行编译吗?

unit-testing - Grails 3:在服务方法中传递输入流

javascript - 停止显示 :none 样式的 div 内的视频声音

javascript - 用于分隔子集的正则表达式和嵌套方括号

node.js - 如何在 knex.js 中使用 postgres::date

javascript - websocket 问题 : cannot connect to node. js 服务器