[英]Triggering event on an element in memory when testing Backbone Views
我正在为Backbone视图/模型/集合编写一些集成测试。 当我在View
上调用render
时,它只是将模板渲染为其自己的el
属性,因此html仅存储在内存中,而不是存储在页面中。 下面是一个简单的模型,以及一个将click事件绑定到DOM元素的视图:
var model = Backbone.Model.extend({
urlRoot: '/api/model'
});
var view = Backbone.View.extend({
events: {
'click #remove': 'remove'
}
render: function () {
var html = _.template(this.template, this.model.toJSON());
this.$el.html(html);
},
remove: function () {
this.model.destroy();
}
});
我正在使用Jasmine编写测试。 在下面的测试中,我要做的就是监视remove
函数,以查看在传递给视图的模板中存在的元素#remove
的click事件触发时是否调用了该函数。
// template
<script id="tmpl">
<input type="button" value="remove" id="remove"/>
</script>
// test
describe('view', function () {
var view;
beforeEach(function () {
view = new view({
template: $('#tmpl').html(),
model: new model()
});
});
it('should call remove when #remove click event fired', function () {
view.$('#remove').click();
var ajax = mostRecentAjaxRequest();
expect(ajax.url).toBe('/api/model');
expect(ajax.method).toBe('DELETE');
});
});
但是,由于#remove
元素在内存中,并且实际上尚未添加到DOM中,所以我不确定如何模拟click事件。 实际上,我什至不确定是否可行?
想要在测试中执行此操作似乎有些奇怪,但是在我的测试中,我试图测试行为而不是实现 ,因此,我不在乎这之间发生了什么-我只是想测试一下用户单击#remove
将DELETE
请求发送回服务器。
在我看来,您忘了在click()
按钮click()
之前在视图上调用render()
了。 并且该模型需要具有id
或主干,实际上不会尝试对服务器进行删除调用。 我已经像以前一样测试了很多视图,没有任何问题。
我只是针对茉莉花2.0和茉莉花ajax 2.0进行了类似的测试。
实时代码:
var MyModel = Backbone.Model.extend({
urlRoot: '/api/model'
});
var MyView = Backbone.View.extend({
events: {
'click #remove': 'remove'
},
initialize: function(options) {
this.template = options.template;
},
render: function () {
var html = _.template(this.template, this.model.toJSON());
this.$el.html(html);
},
remove: function () {
this.model.destroy();
}
});
眼镜:
describe("testing", function() {
var view;
beforeEach(function() {
jasmine.Ajax.install();
view = new MyView({
template: '<input type="button" value="remove" id="remove"/>',
model: new MyModel({id: 123})
});
view.render();
});
it('should call remove when #remove click event fired', function () {
view.$('#remove').click();
var ajax = jasmine.Ajax.requests.mostRecent();
expect(ajax.url).toBe('/api/model/123');
expect(ajax.method).toBe('DELETE');
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.