How to test a click event in the Jasmine Test runner in Backbone?

142 Views Asked by At

I have a spec in which I want to test if a method is called when a button is clicked.

I have registered the click event in the View file:

events: {
    'click #toggle': 'onClickToggle'
}

My test file looks like:

describe('Todo Item\'s view\'s suite', function() {

    let view;

    beforeEach(function() {
        const todoItem = new TodoItem({ description: 'Some Todo ' });
        view = new TodoItemView({ model: todoItem });

        const html = '<label><input type="checkbox" id="toggle" />Some Desc</label><button id="delete">Delete</button>';
        view.$el.html(html);
    });

    it('clicking on element or checkbox should invoke the onClickToggle method', function() {
        spyOn(view, 'onClickToggle');

        view.$('#toggle').click();

        expect(view.onClickToggle).toHaveBeenCalled();
    });
});

I have referenced all the required files in the test runner HTML including jQuery, Jasmine, jQuery-Jasmine. But when the spec file is run in te browser, the test fails.

The following error is thrown:

Error: Expected spy onClickToggle to have been called.
    at <Jasmine>
    at UserContext.<anonymous> (http://127.0.0.1:5500/tests/jasmine/spec/views/TodoItemViewSpec.js:28:36)
    at <Jasmine>
0

There are 0 best solutions below