node.js - nodejs覆盖模块中的函数

标签 node.js

我正在尝试测试模块中的功能。此函数(我将其称为 function_a )调用同一文件中的不同函数 ( function_b )。所以这个模块看起来像这样:

//the module file

module.exports.function_a = function (){ 
  //does stuff
  function_b()
};

module.exports.function_b = function_b = function () {
  //more stuff
}

我需要使用 function_b 的特定结果来测试 function_a。

我想从我的测试文件中覆盖 function_b,然后从我的测试文件中调用 function_a,导致 function_a 调用此覆盖函数而不是 function_b。

请注意,我已经尝试并成功地覆盖了来自单独模块的函数,例如 this问题,但这不是我感兴趣的。

我已经尝试了下面的代码,据我所知,它不起作用。不过,它确实说明了我的目标。

//test file
that_module = require("that module")
that_module.function_b = function () { ...override ... }
that_module.function_a() //now uses the override function

有正确的方法吗?

最佳答案

从模块代码外部,您只能修改该模块的exports 对象。您不能“进入”模块并更改模块代码中 function_b 的值。但是,您可以(在您的最后一个示例中确实)更改了 exports.function_b 的值。

如果您将 function_a 更改为调用 exports.function_b 而不是 function_b,您对模块的外部更改将按预期发生。

关于node.js - nodejs覆盖模块中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25649097/

相关文章:

node.js - Q Promise Nodejs如何在循环中解析

javascript - 链接index.html client.js 和 server.js

javascript - Nodejs get throw er;//未处理的 'error'事件

node.js - 使用 JSON.stringify 将符号转为字符串

node.js - Mongoose 转换为 ObjectId 值失败

javascript - Sequelize : Find All That Match the query (Case Insensitive)

node.js - 在 Node.js 上的 Express 中扩展 View 类

node.js - Mongoose 使用 $lookup 包含辅助文档中的字段

node.js - 使用feathersjs rethinkdb适配器通过非sql选择不同的

javascript - 使用 Express API 和 ReactJS SPA 进行路由