I have a custom event defined. I want to spy on it with jasmine. But the problem I have is that it is failing when I am using spyOn
to spy on that event. When I spy on some function it is working fine. Heres what I tried:
describe("Test:", function(){
it("Expects event will be spied: ", function() {
var eventSpy = spyOn(window, 'myEvent').andCallThrough();
expect(eventSpy).toHaveBeenCalled();
//Also tried this:
//expect(eventSpy).not.toHaveBeenCalled();
});
});
So I tried both not.toHaveBeenCalled()
and toHaveBeenCalled()
but it fails in both the cases. So I guess spyOn
is unable to spy on the custom event.
*Note: * I looked at other SO answers with a similar question, but it was something to do with a click event. But in my case it is a custom event that will get fired based on some conditions automatically.
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();
In Jasmine, you can do anything with a property spy that you can do with a function spy, but you may need to use different syntax. Use spyOnProperty to create either a getter or setter spy. it("allows you to create spies for either type", function() { spyOnProperty(someObject, "myValue", "get").
SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result.
Try something like this. Worked for me
describe("Test:", function(){
it("Expects event will be spied: ", function() {
var eventSpy = jasmine.createSpy();
sampleElement.addEventListener('sample event', eventSpy);
expect(eventSpy).toHaveBeenCalled();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With