Jasmine can't spy on event handler?

百般思念 提交于 2019-12-03 12:49:47

You are actually testing that GRAPH.padElement calls the supplied clickHandler and not that this.clickHandler of GRAPH.Pad is called by GRAPH.padElement. How I would do that is

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

This may sound little different to what you are trying to achieve. But in ideal unit testing world you should be testing each unit independently, so I would first test that padElement does what it's supposed to do (as above) and then write another test to make sure GRAPH.Pad is passing correct handler to padElement. Now to do that I would not create padElement directly from within GRAPH.Pad but somehow inject it from outside and then mock it in the jasmine specs. If you are not clear on this part let me know and I can put some code together for you.

To add a more generic explanation:

You need to spy before attaching the function as an event listener.

Some pseudo-code:

it("succeeds", function(){
  var o = {}
  o.f = function() { console.log("event caught!");} //your eventHandler
  spyOn(o, "f").and.callThrough(); //o.f is now a spy
  addEventListener('click', o.f); //spy listens for event 

  fireEvent("click"); //"event caught!" is written to console

  expect(o.f).toHaveBeenCalled(); //success, we're happy
});



it("fails", function(){
  var o = {}
  o.f = function() { console.log("event caught!");} //your eventHandler
  addEventListener('click', o.f); //your eventHandler function listens for event
  spyOn(o, "f").and.callThrough(); //o.f is now a spy

  fireEvent("click"); //"event caught!" is written to console

  expect(o.f).toHaveBeenCalled(); //fail, we waste a couple of hours not understanding why
});

So if you know your handler is being called, but the spy does not register as .tohaveBeenCalled() check what happens first: your spy or the assignment of the listener. The spy needs to come first.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!