Testing a trigger click from a Backbone.View which opens a new Backbone.View

Question!

I have two Backbone Views, MainView and PopupView.

MainView contains a help button. When the help button handler is fired it shows the Backbone.View.

My question is how should I test this behavior from the MainView module?


Here's my code about MainView:

var MainView = Backbone.View.extend({
    events: {
        'click #help' : 'showPopUp'
    },

    showPopUp: function() {
       var popupView = new PopupView();
       app.vent.trigger('showModal', popupView);
    }    
});

Here's my code about the mainView.spec:

describe("When help button handler fired", function() {
    beforeEach(function() {
        this.view.render();
        this.view.$el.find('#help').trigger('click');
    });
    it("shows the popup", function() {
        // what should I do?
    });
});

Here's my code about the app:

var app = new Marionette.Application();

app.addRegions({
    header: '#header',
    sidebar: '#sidebar',
    main: '#main',
    modal: '#modal'
});

app.vent.on('showModal', function(view) {
    var modal = app.modal;

    modal.show(view);
    modal.$el.modal({
        show: true,
        keyboard: true,
        backdrop: 'static'
    });
});


Answers

How about this:

describe("When help button handler fired", function() {
    var popupShown;

    beforeEach(function() {
        popupShown = false;

        this.view.render();
        app.vent.on('showModal', function() {
            popupShown = true;      
        });
        this.view.$el.find('#help').trigger('click');
    });
    it("shows the popup", function() {
        expect(popupShown).toBe(true);
    });
});

That said, I would recommend a few things:

  1. As was mentioned elsewhere, don't create the modal view in MainView. This couples the two too tightly.
  2. In your tests, you may want to say something like it("triggers the help event") or something similar. This is particularly important since you're unit testing that object in isolation. For integration testing, the opposite would be true.
  3. I'm not sure that you aren't doing too much in your beforeEach function. You may want to at least trigger the button click in the it scope, although based on what you're describeing, this may be OK.


This video can help you solving your question :)
By: admin