编写Qunit单元测试时管理全局Backbone事件

时间:2013-05-18 23:56:38

标签: backbone.js qunit

我正在为我的Backbone应用程序编写单元测试。某些测试会触发事件,这会导致不同测试之间的干扰。

以下是我的测试

test('user setting a company should update the departmentslists url', function() {
    var Acme = new Company({ id:274, name: "Acme Solutions" });
    var companies = new CompanyList;
    var departments = new DepartmentList;
    new CompanySelectorView({ el: '#company-input', collection: companies });

    events.trigger('userSet:company', Acme);

    equal(_.result(departments, 'url'), 'http://'+document.location.host+'/data/companies/274/departments');
});

asyncTest('user setting a company should retrieve that companys departments', function() {
    var Acme = new Company({ id:274, name: "Acme Solutions" });
    var companies = new CompanyList;
    var departments = new DepartmentList;
    new CompanySelectorView({ el: '#company-input', collection: companies });

    events.trigger('userSet:company', Acme);

    events.on('fetched:departments', function(response) {
        deepEqual(response, [{id: "8",name: "Accounting"},{id: "1",name: "Client Services"},{id: "470",name: "Systems"},{id: "1187",name: "Managers"}]);
        start();
    })

});

以及我收藏的相关部分:

var DepartmentList = Backbone.Collection.extend({

    initialize: function() {
        var self = this;

        events.on("userSet:company", function(company) {
            self.selectedCompany = company;
            self.fetch({
                success: function(collection, response, options) {
                    events.trigger("fetched:departments", response);
                }
            });
        });
    },

    model: Department,

    selectedCompany: '',

    url: function() {
        return 'http://'+document.location.host+'/data/companies/'+this.selectedCompany.id+'/departments';
    }

});

这里有什么解决方案?我想将这两个测试彼此分开,因为它们是不同的东西,但我也想在我的测试中包含事件触发器。

PS:我是Backbone&的新手。单元测试,任何批评都非常受欢迎。

1 个答案:

答案 0 :(得分:0)

解决此问题的简单方法是使用events.once代替events.on。这样,每次测试后都会清理您的事件。