简体   繁体   English

无法窥探现有功能

[英]Unable to spy on existing function

I'm unable to spy on an existing function in the current scope within node.js : 我无法监视node.js当前范围内的现有功能:

function myFunc() {console.log("Spy on me and I'll have you arrested"};
sinon.spy(myFunc);
myFunc.restore(); // throws an error: myFunc.restore is not a function

I can however spy on a function which is a member of an object: 但是,我可以监视作为对象成员的函数:

var anObject = {
  myFunc: function() {console.log('Being spied on turns me on');}
};
sinon.spy(anObject, 'myFunc');
sinon.myFunc.restore(); // smooth sailing

According to the docs , it seems to me like that should work fine. 根据文档 ,在我看来,这应该可以正常工作。 How do I get this done? 我该如何完成?

In JavaScript when a function is passed as an argument it is a reference-passed-by-value, like so: 在JavaScript中,将function作为参数传递时,它是按值传递的引用,如下所示:

function foo() { console.log("foo"); } // func1, referenced by `foo`
function bar() { console.log("bar"); } // func2, referenced by `bar`

function mutate(func) {
    func = bar;
}

mutate( foo );
foo();

This will print out "foo" , not "bar" , because mutatate does not change foo 's reference to func1 . 这将打印出"foo" ,而不是"bar" ,因为mutatate不会更改foofunc1的引用。

Here is the relevant source code for Sinon's spy.js : https://github.com/sinonjs/sinon/blob/master/lib/sinon/spy.js 这是Sinon的spy.js的相关源代码: https : //github.com/sinonjs/sinon/blob/master/lib/sinon/spy.js

The create function sees if the first argument is a function, and if so, it wraps it in a proxy ( create: function create(func, spyLength) { , line 148). create函数查看第一个参数是否为函数,如果是,则将其包装在代理中( create: function create(func, spyLength) { ,第148行)。 It then returns the proxy. 然后,它返回代理。

So in your case, you need to replace myFunc with the new proxy: 因此,您需要用新的代理替换myFunc

function myFunc() {console.log("Spy on me and I'll have you arrested"};
myFunc = sinon.spy(myFunc); // here

However you cannot use myFunc.restore() to undo the spy because .restore cannot change the target of the myFunc reference. 但是,您不能使用myFunc.restore()撤消间谍,因为.restore无法更改myFunc引用的目标。 Note that restore also does not return a value, so you must keep track of myFunc yourself: 请注意, restore也不返回值,因此您必须自己跟踪myFunc

function myFuncOriginal() {console.log("Spy on me and I'll have you arrested"};
var myFunc = sinon.spy(myFuncOriginal);
myFunc = myFuncOriginal; // instead of `myFunc.restore();`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM