2017-09-24 86 views
0

我发现了一些相关的问题,但似乎没有任何帮助我想要实现的东西。因此,我想窥视一个构造函数方法,以便当使用构造函数创建的对象在另一个函数中调用此方法的另一个作用域时,我可以知道该调用的参数。Sinon - 构造函数方法间谍

实施例:

function Constructor(args){ 
    this.method = sinon.spy() 
} 

function someFunction(){ 
    obj = new Constructor(args); 
    obj.method() 
} 

console.log(Constructor.method.args[0]); // list the args of the obj.method() call 

任何帮助将不胜感激。

编辑:我才意识到自己措辞的问题错了,最后问的东西完全琐碎:-)

+0

我刚刚看到你添加了什么。这是不可能的,在你的'console.log(Constructor.method.args [0]);'你正在使用方法作为静态函数,事实并非如此。想象一下,如果你有5个不同的构造函数实例化。 –

回答

1

这样,您就可以在Constructor.method间谍:

function Constructor(args){ 
    this.method = function() {} 
} 

const obj = new Constructor(); 
obj.method = sinon.spy(obj.method); 
obj.method('someArg'); 

console.log(obj.method.args[0]); // [ 'someArg' ] 

但这样做就像你说的是不可能的,你不能有一个同名的静态方法和一个类方法,如果你不止一次实例化这个类,那么怎么办......无论如何,我可以得到的最好的解决方案是使用构造函数上的Proxy,就像:

function Constructor(args) { 
    this.method = function() {} 
} 

const ProxyConstructor = new Proxy(Constructor, { 
    construct: function (target, args, newTarget) { 
     const c = new target(...args); 
     const origMethod = c.method; 
     c.method = function (...args) { 
      ProxyConstructor.methodArgs = ProxyConstructor.methodArgs || []; 
      ProxyConstructor.methodArgs = ProxyConstructor.methodArgs.concat(args) 
      origMethod(...args); 
     }; 
     return c; 
    } 
}); 


function someFunction() { 
    obj = new ProxyConstructor(); 
    obj.method('test') 
} 

someFunction(); 
console.log(ProxyConstructor.methodArgs); // ['test'] 

您可以将该代码粘贴到文件中并尝试。此外,在编写测试时,您可能需要重构代码以使其可测试,或者您可以在编写代码(TDD)之前先编写测试。

+0

感谢您的回答。然而在你的例子中,console.log和obj声明在同一个范围内。我想要做的是知道该方法是否被称为即使在一个无法访问的范围内... – Nfys

+0

我已经更新了我的答案,请看看。 –