2014-09-03 101 views
4

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

//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 

有没有正确的方法来做到这一点?

回答

3

从模块代码外部,您只能修改该模块的exports对象。您无法“进入”模块并在模块代码中更改function_b的值。然而,你可以(并在你的最后一个例子中)改变了exports.function_b的值。

如果更改function_a以致电exports.function_b而不是function_b,那么对模块的外部更改将按预期发生。

+0

完美的工作!万分感谢! – 2014-09-03 16:30:48