nodejs 覆盖模块中的函数 [英] nodejs override a function in a module

查看:68
本文介绍了nodejs 覆盖模块中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

//模块文件module.exports.function_a = 函数 (){//做东西函数_b()};module.exports.function_b = function_b = function () {//更多东西}

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

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

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

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

//测试文件that_module = require("那个模块")that_module.function_b = function () { ...覆盖 ... }that_module.function_a()//现在使用覆盖函数

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

解决方案

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

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

I am trying to test a function in a module. This function ( I will refer to it as function_a ) calls a different function ( function_b ) within the same file. So this module looks like this:

//the module file

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

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

I need to test function_a with a specific result from function_b.

I would like to override function_b from my test file, then call function_a from my test file, resulting in function_a calling this override function instead of function_b.

Just a note, I have tried and succeeded in overriding functions from separate modules, like this question, but that is not what I am interested in.

I have tried the code below, and as far as I know, doesn't work. It does illustrates what I am going for, though.

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

Is there a correct way to do this?

解决方案

From outside a module's code, you can only modify that module's exports object. You can't "reach into" the module and change the value of function_b within the module code. However, you can (and did, in your final example) change the value of exports.function_b.

If you change function_a to call exports.function_b instead of function_b, your external change to the module will happen as expected.

这篇关于nodejs 覆盖模块中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆