spliter
spliter

Reputation: 12569

Testing event handler on an object with Jasmine

I have a class like:

MyClass = function() {
    var view = {
        delegateEvents: function () {
            this.$el.on('click', 'input[type="radio"]', this.toggleServices);
        },
        toggleServices: function () {
            …
        },
        render: function () {
            blah-blah-blag (rendering the view)…
            this.delegateEvents();
        }
    };
    view.init();
    return view;
}

(how I am getting $el is beyond the scope of the question, but be sure it works) I am testing an instance of this class in Jasmine like:

it('it handles clicks on radio buttons', function () {
    var view = new MyClass();
    view.render();

    spyOn(view, 'toggleServices');
    view.$('input[type="radio"]').eq(0).click();
    expect(view.toggleServices).toHaveBeenCalled();
});

The problem is now that in the test, the spy is not being called, but the code goes into original toggleServices() of the class instead of being a spy. Seems like I don't understand how to create a spy that would cought requests to this.toggleServices in init().

Any suggestions?

Upvotes: 0

Views: 2752

Answers (1)

Daniel Aranda
Daniel Aranda

Reputation: 6552

You should spy before setup the listeners, in other words, just spy before call render.

it('it handles clicks on radio buttons', function () {
    var view = new MyClass();
    spyOn(view, 'toggleServices');
    view.render();

    view.$('input[type="radio"]').eq(0).click();
    expect(view.toggleServices).toHaveBeenCalled();
});

Upvotes: 3

Related Questions