Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/412.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Jasmine-spyOn构造方法_Javascript_Jasmine - Fatal编程技术网

Javascript Jasmine-spyOn构造方法

Javascript Jasmine-spyOn构造方法,javascript,jasmine,Javascript,Jasmine,对于以下代码: class Endpoint { constructor(type, start_value) { this.type = type this.end_value = start_value + 2 this.constructor.prefill(type, this.end_value) } static prefill(type, end_value) { console.log("called") $("#end_val

对于以下代码:

class Endpoint {
  constructor(type, start_value) {
    this.type = type
    this.end_value = start_value + 2
    this.constructor.prefill(type, this.end_value)
  }
  static prefill(type, end_value) {
    console.log("called")
    $("#end_value").text(end_value)
  }
}
以下规范失败(spy未被调用,即a
.NOT.toHaveBeenCalled()
通过),即使我可以通过
控制台.log
输出确认,并且DOM
$(“#end_值”)
正确填充调用

describe("when constructing end point class", function() {
  beforeEach(function() {
    endpoint = new Endpoint("typeA", 3)
    spyOn(endpoint.constructor, "prefill")
  })
  it("calls prefill", function() {
    expect(endpoint.constructor.prefill).toHaveBeenCalledWith("typeA", 5)
  })
})
使用以下命令

jasmine (2.7.0)
jasmine-core (2.8.0)
jasmine-jquery-rails (2.0.3)

在这里,间谍设置的时机很重要。初始化类调用构造函数。间谍错过了调用,因为它是在创建新实例后设置的,请尝试切换顺序():


旁注:我以前没有见过
this.constructor.myStaticMethod
语法,通常从类定义调用静态方法:
Endpoint.prefill(param1,param2)
。无论哪种调用方式,测试都通过了,但我很想了解其中的选择。

更新了答案并添加了一个plunker供您使用。这很有效
this.constructor.prefill
与表示
Endpoint.prefill
相同,因为
this.constructor
是对类本身的引用。这是我的理解!事实上,即使您混淆了间谍和期望(即,交替使用
endpoint.constructor
vs
endpoint
)。我这样写是为了更明确地说明prefill是实际类上的一个方法
import { Endpoint } from './endpoint';

describe("when constructing end point class", function() {

  let endpoint;

  beforeEach(function() {
    spyOn(Endpoint, "prefill"); // add spy before initializing class
    endpoint = new Endpoint("typeA", 3);
  })
  it("calls prefill", function() {
    expect(Endpoint.prefill).toHaveBeenCalledWith("typeA", 5);
  })
});