Jasmine - 在构造函数中监视方法调用 [英] Jasmine - Spying on a method call within a constructor

查看:129
本文介绍了Jasmine - 在构造函数中监视方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试在我的Javascript对象构造函数中是否调用了以下方法。从我在Jasmine文档中看到的,我可以窥探一个构造函数方法,并且我可以在实例化对象之后监视方法,但是在构造对象之前我似乎无法监视方法。

I want to test whether the following method is called with in my Javascript object constructor. From what I have seen in the Jasmine documentation, I can spy on a constructor method and I can spy on methods after an object has been instantiated, but I can't seem to be able to spy on a method before the object is constructed.

对象:

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

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

我想在规范中做这样的事情:

I want to do something like this in the spec:

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


推荐答案

直接间谍原型方法:

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();
  });
});

这篇关于Jasmine - 在构造函数中监视方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆