Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spy on a custom event in jasmine?

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.

like image 545
Indradhanush Gupta Avatar asked Jul 29 '13 06:07

Indradhanush Gupta


People also ask

How do you spy event in Jasmine?

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

How do I spy on service property in Jasmine?

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").

What is spyOn in Jasmine?

SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result.


1 Answers

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

});
like image 177
Katya Pavlenko Avatar answered Oct 18 '22 04:10

Katya Pavlenko