[英]Hook function call in node.js
is there a way to hook function call or redefine a function before a call in node.js? 有没有一种方法可以在node.js中的调用之前挂接函数调用或重新定义函数? I need this for unit testing, may be Proxy or some testing libary is and option? 我需要此来进行单元测试,可能是Proxy或某些测试库,并且可以选择吗?
Example: 例:
//some js file
function a(){
b()// need to be hooked
}
function b(){
//do some stuff
}
What you can do is create a wrapper around the target function, and perform whatever operations you need to do before execution, ex: 您可以做的是围绕目标函数创建一个包装器,并执行执行之前需要执行的所有操作,例如:
const tmp = b
function b {
doSomething()
maybeBroadcastAnEvent()
tmp() //run original function
}
You can use .apply()
with the arguments
object to forward the call data of a
into the b
function. 您可以使用.apply()
与arguments
反对的呼叫数据转发a
到b
功能。
function a(){
return b.apply(this, arguments)
}
function b(){
//do some stuff
}
So whatever this
value and arguments were given to a
will be forwarded to b
, and whatever b
returns will be returned by a
. 所以,无论this
是给定值和参数将a
将被转发到b
,不管b
回报将返回a
。
As it seems you attempted in your newer question, you can create a function that binds b
to the Function.prototype.call
method to accomplish this more succinctly. 似乎您在尝试新问题时,可以创建一个将b
绑定到Function.prototype.call
方法的Function.prototype.call
以更简洁地完成此任务。
var a = Function.call.bind(b);
function b(){
//do some stuff
}
Now when a
is invoked, the first argument provided will become the this
value of b
and the rest of the arguments provided will become the regular arguments of b
. 现在,当调用a
时,提供的第一个参数将成为b
的this
值,其余的参数将成为b
的常规参数。
If you don't care about the this
value, and just want to pass on all the args, you can bind null
as the first argument to .call
, so that b
will just get forwarded all the provided arguments as regular args. 如果您不关心this
值,而只想传递所有的args,则可以将null
作为第一个参数绑定到.call
,以便b
会将所有提供的参数作为常规args转发。
var a = Function.call.bind(b, null);
function b(){
//do some stuff
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.