我正在尝试测试模块中的功能。此函数(我将其称为 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/