我正在测试主干中选择框视图的事件更改,该视图“应该在更改时提供到 router.navigate 的正确路径”。这是场景,如果我在下拉列表中选择一个值,它应该重定向到正确的 url。
这是测试(campaign.test.js):
it('should provide the correct path to router.navigate when changed', function() {
var routeName = 'test_campaign';
var routerSpy = sinon.spy(Insights.router, 'navigate');
this.view.$el.bind('change', function() {
expect(routerSpy).toHaveBeenCalledWith('campaign/' + routeName, true);
});
//create the option element holding the test value
this.view.$el.append($('<option value="' + routeName +'" selected="selected" />'));
this.view.$el.trigger('change');
routerSpy.restore();
});
这是模块(campaign.js):
DropdownView: Backbone.View.extend({
tagName: 'select',
className: 'campaign-list',
events: {
'change' : 'navCampaign'
},
initialize: function() {
_.bindAll(this);
this.collection.on('reset', this.render);
this.collection.on('add', this.addCampaign);
//if no campaigns exist then add a dummy placeholder
if(this.collection.models.length === 0) {
this.$el.append('<option value="">No Campaigns</option>');
}
},
navCampaign: function() {
Insights.router.navigate();
},
addCampaign: function(campaign) {
//remove the No Campaigns placeholder when campaigns are added
var firstChild = this.$el.children(':first');
if(firstChild.attr('value') === '') {
firstChild.remove();
}
var view = new Insights.Campaign.DropdownItem({ model: campaign });
var item = view.render().el;
this.$el.append(item);
},
render: function() {
this.collection.each(this.addCampaign);
return this;
}
})
在我的测试中,我创建了一个新的 OPTION 元素,然后设置了一个选中属性的值。
如何将其作为更改事件的 currentTarget 传递并将其发送到 trigger()?
或者有没有更简单的方法来做到这一点?
我得到这个测试失败。错误:预期函数已使用“campaign/test_campaign”调用,true。