How to assert a spy is invoked with event on click using jasmine?
If you can't use jQuery you may use dispatchEvent
and check its return value (based on this answer).
const domElem = document.getElementById('some_dom_element');
const clickEvent = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
const cancelled = !domElem.dispatchEvent(clickEvent);
expect(cancelled).toBeTruthy();
You have to trigger your own event passing a spy for the stopPropagation
method, cause you wanna test if the event was stopped.
var event = {
type: 'click',
stopPropagation: function(){}
}
var spy = spyOn(event, 'stopPropagation');
$('#some_dom_element').trigger(event);
expect(spy).toHaveBeenCalled();
Note: there is code smell when you spy on the object you want to test, because you start to test the inner behavior of your class. Think about your function as a black box and test only the things you put in and get out. In your case, renaming the function in will break the test, while the code is still valid.