使用JavaScript和sinon如何监视构造函数中调用的方法?

我真的需要帮助下面的代码 – 这不是从我的程序粘贴我的头顶,但我认为这清楚地表明了问题(我相信它是完全准确的)。 当我请求“spy.called”的值时,忽略构造函数中的调用。 我如何编码,以便在构造函数内部的调用由间谍注册?

或者如果不可能,我应该采取什么方法? 示例代码非常感谢 – 非常感谢 – 一整天都用这个敲我的头!

function MyClass() { var self = this; this.myFunc = function() { console.log("hi"); } function init() { self.myFunc(); } init(); } var spy = sinon.spy(new MyClass(), "myFunc"); console.log(spy.called); // true if the spy was called at least once // ABOVE OUTPUTS FALSE - IT FAILS TO REGISTER THE CALL IN THE CONSTRUCTOR! spy.myFunc(); console.log(spy.called); // ABOVE OUTPUTS TRUE AS EXPECTED 

这里的问题是,当方法myFunc被称为间谍不存在。 您的代码相当于:

 var c = new MyClass() var spy = sinon.spy(c, "myFunc"); 

很明显,当构造函数被调用时,间谍不在位。

为了解决这个问题,你可以在MyClass对象的原型中移动myFunc方法,然后窥探原型中的方法。

例如:

 function MyClass() { this.init(); } MyClass.prototype.myFunc = function() { console.log("hi"); } MyClass.prototype.init = function() { this.myFunc(); } var myFuncSpy = sinon.spy(MyClass.prototype, "myFunc"); var initSpy = sinon.spy(MyClass.prototype, "init"); var c = new MyClass(); console.log(myFuncSpy.called); // TRUE console.log(initSpy.called); // TRUE 

JSFIDDLE: http : //jsfiddle.net/och191so/1/打开控制台查看结果。

我想你应该重新devise你的class级。 您可以在构造函数参数中接受myFunc(仅在使用时才有意义),也可以在MyClass的原型上进行设置:

 function MyClass() { function init() { this.myFunc(); } init(); } MyClass.prototype.myFunc = function() { console.log("hi"); } var spy = sinon.spy(MyClass.prototype, "myFunc"); new MyClass(); console.log(spy.called);