0

我正在为我的 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 和单元测试的新手,任何批评都非常受欢迎。

4

1 回答 1

0

解决这个问题的简单方法是使用events.once而不是events.on. 这样,您的事件在每次测试后都会被清除。

于 2013-05-21T15:21:53.703 回答