从Backbone.View测试触发器点击,打开一个新的Backbone.View

时间:2012-07-19 10:13:31

标签: javascript backbone.js jasmine marionette

我有两个主干视图,MainViewPopupView

MainView包含一个帮助按钮。当触发帮助按钮处理程序时,它会显示Backbone.View。

我的问题是如何从MainView模块测试此行为?


这是关于MainView的代码:

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

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

这是关于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?
    });
});

以下是我关于该应用的代码:

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'
    });
});

3 个答案:

答案 0 :(得分:5)

如果你正在使用Sinon和Chai,你可以试试这个:

describe("When help button handler fired", function() {
  beforeEach(function() {
      this.popupSpy = sinon.spy()
      app.vent.on('showModal', this.popupSpy);
      this.view.render();
      this.view.$el.find('#help').trigger('click');
  });
  it("shows the popup", function() {
      this.popupSpy.callCount.should.equal(1);
      this.popupSpy.args[0][0].should.be.an.instanceOf(PopupView);
  });
});

答案 1 :(得分:3)

所以你的主视图不应该打开弹出窗口,它甚至不应该知道存在这样的东西。它应该通过事件总线通知其他模块,通过触发事件来打开弹出窗口。

当你使用app.vent时,我假设你正在使用木偶。在我的项目中,我有一个Marionette.Region来处理叠加视图。该区域应该打开/关闭视图。

这样做,它更容易测试。在主视图中,您可以监视app.vent函数并测试单击按钮时它将执行的功能。在您所在的地区,您可以在app.vent点击该活动并监视您的view.render功能。

在您想要测试的对象中创建新实例,使测试总是更加困难。当然,它在JavaScript中更容易,例如在Java中,因为你可以在JavaScript中覆盖运行时的现有函数,但是使用某种依赖注入方式可以更容易地模拟和监视依赖项。

答案 2 :(得分:1)

这个怎么样:

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

那就是说,我会推荐一些东西:

  1. 如其他地方所述,不要在MainView中创建模态视图。这把两者结合得太紧了。
  2. 在您的测试中,您可能想要说it("triggers the help event")之类的内容。这一点尤为重要,因为您要单独测试该对象。对于集成测试,情况恰恰相反。
  3. 我不确定你在beforeEach函数中做得不是太多。您可能希望至少触发it范围内的按钮点击,但根据您describe的内容,这可能没问题。