nodejs覆盖模块中的函数



我正在尝试测试模块中的一个函数。这个函数(我将其称为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
}

我需要用函数b的特定结果来测试函数a。

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

请注意,我已经尝试并成功地覆盖了来自独立模块的功能,比如这个问题,但这不是我感兴趣的。

我试过下面的代码,但据我所知,它不起作用。不过,它确实说明了我要做什么。

//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,则对模块的外部更改将按预期进行。

您实际上可以使用包重新布线。它允许您获取和设置模块中声明的内容

foo.js

const _secretPrefix = 'super secret ';
function secretMessage() {
    return _secretPrefix + _message();
}
function _message() {
    return 'hello';
}

foo.test.js

const rewire = require('rewire');
// Note that the path is relative to `foo.test.js`
const fooRewired = rewire('path_to_foo');
// Outputs 'super secret hello'
fooRewired.secretMessage();
fooRewired.__set__('_message', () => 'ciao')
// Outputs 'super secret ciao'
fooRewired.secretMessage();

最新更新