Jasmine无法窥探事件处理程序?

10 javascript testing event-handling jasmine

尝试测试使用Jasmine在单击的元素上调用事件处理程序.有一个"Pad"对象,其中包含一个DOM元素"PadElement",它被点击.事件处理程序是Pad对象上的一个方法:

GRAPH.Pad = function(graphDiv, graph) {
    this.graph = graph;

    this.clickHandler = function(e) {
        console.log('padElement clickHandler called');
        //this.graph.createVertex(e.clientX, e.clientY);
    };
    this.padElement = GRAPH.padElement(graphDiv, this.clickHandler);
}

GRAPH.padElement = function(graphDiv, clickHandler) {
    //Initialize pad
    var NS="http://www.w3.org/2000/svg";
    var pad=document.createElementNS(NS,"svg");
    pad.setAttributeNS(null, 'id', 'pad');
    graphDiv.appendChild(pad);
    pad.addEventListener('click', clickHandler)
    return pad;
}
Run Code Online (Sandbox Code Playgroud)

茉莉花测试:

var testDiv = document.createElement('div');
var testGraph = new GRAPH.Graph(testDiv);
var testPad = new GRAPH.Pad(testDiv, testGraph);

  it('has its clickHandler function called when its padElement is clicked',
    function() {
      spyOn(testPad, "clickHandler");
      simulateClick(testPad.padElement);
      //testPad.clickHandler();
      expect(testPad.clickHandler).toHaveBeenCalled();
  });
Run Code Online (Sandbox Code Playgroud)

但是,测试失败.请注意,事件监听器确实被调用(console.log使用鼠标单击并使用simulateClick成功写入),如果我只是直接调用testPad.clickHandler(),Jasmine的间谍可以接收它.但是在实际测试中会发生什么?事件处理程序调用是否在运行时传输到另一个对象?这样做的正确方法是什么?

Suh*_*has 6

你实际上是测试该GRAPH.padElement调用提供的clickHandler,而不是说this.clickHandlerGRAPH.Pad被称为GRAPH.padElement.我该怎么做呢

var testDiv = document.createElement('div');
var clickHandlerSpy = jasmine.CreateSpy();
var padelement = padElement(testDiv , clickHandlerSpy);

  it('has its clickHandler function called when its padElement is clicked',
    function() {
      simulateClick(testPad.padElement);
      expect(clickHandlerSpy).toHaveBeenCalled();
  });
Run Code Online (Sandbox Code Playgroud)

这可能听起来与您想要实现的完全不同.但是在理想的单元测试世界中,你应该独立地测试每个单元,所以我首先测试它padElement做了它应该做的事情(如上所述),然后编写另一个测试以确保GRAPH.Pad传递正确的处理程序padElement.现在要做到这一点,我不会padElement直接从内部创建,GRAPH.Pad但不知何故从外部注入它,然后在茉莉花规格中模拟它.如果您对此部分不清楚,请告诉我,我可以为您整理一些代码.