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

Jasmine - Spying on a method call within a constructor(Jasmine - 在构造函数中监视方法调用)
本文介绍了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 - 在构造函数中监视方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

jasmine.createSpyObj with properties(jasmine.createSpyObj 与属性)
What#39;s a good way to reuse test code using Jasmine?(使用 Jasmine 重用测试代码的好方法是什么?)
Does Jasmine#39;s toThrow matcher require the argument to be wrapped in an anonymous function?(Jasmine 的 toThrow 匹配器是否需要将参数包装在匿名函数中?)
How to mock window.location.href with Jest + Vuejs?(如何用 Jest + Vuejs 模拟 window.location.href?)
Getting requirejs to work with Jasmine(让 requirejs 与 Jasmine 一起工作)
How can I spy on a getter property using jasmine?(如何使用 jasmine 监视 getter 属性?)