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

时间:2015-05-26 18:19:20

标签: javascript node.js sinon

我真的需要以下代码的帮助 - 这不是从我的程序中粘贴它的顶部,但我认为它清楚地证明了问题(我相信它是完全准确的)。当我要求" spy.called"的价值时它忽略了构造函数中的调用。我如何对此进行编码,以便构造函数中的调用由spy注册?

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

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

2 个答案:

答案 0 :(得分:3)

The problem here is that when the method myFunc is called the spy doesn't exist yet. Your code is equivalent to :

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

Clearly the spy is not in place when the constructor is called.

To solve this problem you can move the method myFunc in the prototype of the MyClass object and then spy the methods in the prototype.

For example:

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/ 打开控制台以查看结果。

答案 1 :(得分:2)

我认为你应该重新设计一下你的课程。您可以在构造函数参数中接受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);