javascript - Jasmine - 监视构造函数中的方法调用

标签 javascript testing jasmine spy

我想测试是否在我的 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();
});

最佳答案

直接窥探原型(prototype)方法:

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

关于javascript - Jasmine - 监视构造函数中的方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8733978/

相关文章:

http - 共享 api 响应的 whurl 替代方案

c# - 如何告诉 unit ms test 从子文件夹而不是 root 中获取 CSV 文件?

javascript - 如何使用 Jasmine 1.3.1 和 Atom 进行异步测试

JavaScript 错误 : DOM Exception 8 using jQuery and an Array

javascript - 下载大文件

javascript - ES6 中的命名对象参数 - 如何检查它们是否已提供?

typescript - 不可分配给编辑器中类型为 'Expected<Promise<string>>' 的参数

javascript - 输入值更新困境

java - 从抽象类型变量中使用具体类

angularjs - 分度器返回转发器的值数组