Yuvraj Patil
Yuvraj Patil

Reputation: 8736

How to cover Marionette View's event using test cases of Jasmine?

I am working on Test cases for Marionette's View. By using events attribute, I have written a callback function on click of an HTML element. The functionality is working but I am struggling in writing test cases. I am not able to cover that click event using Jasmine test cases.

I have used the Marionette Region to render the view. I have tried using spies but those are not working.

Please find code below for more details:

var TestView = Backbone.Marionette.CompositeView.extend({
     tagName: 'div',
        className: 'test-menu',
        childView: testMenuView,
        childViewOptions: function() {
            return {
                'componentId': this.cid
            };
        },
        template: _.template(testTemplate),
        initialize: function(options) {
            this.collection = this.options.testData;
        },
        onShow: function(collectionView) {
            collectionView.$el.show();
        },            
       attachHtml: function(collectionView,itemView) {
         collectionView.$("#testMenu").append(itemView.el);
       },
        events: {
            'click #testBtn': function (event) {
                    alert('testBtn Clicked');
            }
        }
    });

Upvotes: 1

Views: 964

Answers (1)

ivarni
ivarni

Reputation: 17878

I like to use JQuery where I can when I write tests due to it being less verbose, and for most events triggering the handlers with JQuery will also work fine.

Given that you've got everything else set up for running a Jasmine suite I'd do

it('reacts to click events on its button', function() {
    var view = new TestView();
    view.render();
    view.$('#testBtn').click(); // or view.$('#testBtn').trigger('click')

    //(verify that the view did what was expected)
});

If testing the alert is the actual problem then use a spy for that, e.g. spyOn(window, 'alert') and expect(window.alert).ToHaveBeenCalledWith('testBtn Clicked')

JQuery won't always be able to trigger event handlers that are bound with addEventListener. Click is not one of those events, but there are situations where I have to trigger events using for examples

var event = document.createEvent('Event');
event.initEvent('keydown');
event.keyCode = 40;
event.altKey = true;
view.el.querySelector('input').dispatchEvent(event);

But most of the time just using JQuery's .trigger or corresponding shortcut-function directly on the element you want is fine.

Upvotes: 1

Related Questions