64

Javascript オブジェクト コンストラクターで次のメソッドが呼び出されるかどうかをテストしたいと思います。Jasmine のドキュメントで見たものから、コンストラクター メソッドをスパイでき、オブジェクトがインスタンス化された後にメソッドをスパイできますが、オブジェクトが構築される前にメソッドをスパイすることはできないようです。

オブジェクト:

Klass = function() {
    this.called_method();
};

Klass.prototype.called_method = function() {
  //method to be called in the constructor.
}

仕様で次のようなことをしたい:

it('should spy on a method call within the constructor', function() {
    spyOn(window, 'Klass');
    var obj = new Klass();
    expect(window.Klass.called_method).toHaveBeenCalled();
});
4

2 に答える 2

113

プロトタイプ メソッドを直接スパイします。

describe("The Klass constructor", function() {
  it("should call its prototype's called_method", function() {
      spyOn(Klass.prototype, 'called_method');  //.andCallThrough();
      var k = new Klass();
      expect(Klass.prototype.called_method).toHaveBeenCalled();
  });
});
于 2012-01-04T21:53:39.980 に答える