nodejs覆盖模块中的一个函数
我试图在一个模块中testing一个函数。 这个函数(我将它称为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的特定结果来testingfunction_a。
我想从我的testing文件中覆盖function_b,然后从我的testing文件中调用function_a,导致function_a调用这个覆盖函数而不是function_b。
只是一个笔记,我已经尝试过,并成功地从单独的模块重写function,就像这个问题,但这不是我所感兴趣的。
我已经尝试了下面的代码,据我所知,不起作用。 它确实说明了我要去的。
//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
,那么对模块的外部更改将按预期发生。