Provare a verificare che un gestore eventi venga chiamato su un elemento cliccato con Jasmine. Avere un oggetto "Pad" che contiene un elemento DOM "PadElement", che viene cliccato. Il gestore di eventi è un metodo sull'oggetto Pad:Jasmine non può spiare il gestore di eventi?
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;
}
Il test Jasmine:
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();
});
Tuttavia, il test fallisce. Si noti che il listener di eventi viene chiamato (console.log scrive correttamente con un clic del mouse e con simulateClick), E se io richiama semplicemente testPad.clickHandler() direttamente la spia di Jasmine può prenderlo. Ma cosa succede durante il test vero? Il richiamo del gestore di eventi viene trasferito su un oggetto diverso in fase di runtime? Qual è il modo giusto per farlo?