我的测试声称将数据插入字符串,但实际上还检查模型是否自动更新 DOM。我应该如何处理这种情况?
使用 Jasmine 测试 ItemView:
describe("ItemView handles rendering views with a model", function() {
it("should render a template and interpolate data from a model", function() {
var user = new Backbone.Model({
name : "Peeter",
age : 24
});
var itemView = new ItemView({
model : user,
template : 'Hello my name is <%= model.get("name") %> and I\'m <%= model.get("age") %> years old.'
});
itemView.render();
user.set({
name : "Pjotr",
age : 25
});
expect(itemView.$el).toHaveText('Hello my name is Pjotr and I\'m 25 years old.');
});
});
* 正在测试的代码(BaseView 有自己的测试) *
我的基本观点:
define(['jquery', 'backbone', 'underscore'], function($, Backbone, _) {
'use strict';
var BaseView = Backbone.View.extend({
/**
* Update the dom element
*/
replaceDomElement : function() {
this.trigger("before:replace_dom_element");
var $el = this.$el.empty();
var $clone = $el.clone();
$el.replaceWith($clone);
this.setElement($clone);
this.trigger("after:replace_dom_element");
},
/**
* Default serialize function
* @returns empty object
*/
serialize: function(){
return {};
},
/**
* Render the view, passing the pictures collection to the view and the
* inner template
*/
render : function() {
this.replaceDomElement();
this.trigger("before:render");
var template = _.template(this.options.template);
/**
* Allow for serialization overwriting
*/
var options = this.serialize();
if(this.options.serialize) {
options = _.isFunction(this.options.serialize) ? this.options.serialize() : this.options.serialize;
}
this.$el.append(template(options));
this.trigger("after:render");
}
});
return BaseView;
});
我的项目视图:
define(['jquery', 'yolojs/views/BaseView'], function($, BaseView) {
'use strict';
var ItemView = BaseView.extend({
className : "item",
/**
* Helper function to determine which data should the view pass to the template
*/
serialize : function() {
return {
model : this.model
};
},
/**
* Set up our view to autoupdate on change
*/
initialize: function() {
/**
* Assign the cid as a data attribute on the model
*/
this.$el.attr("data-cid", this.model.cid);
this.model.on('change',this.render,this);
}
});
return ItemView;
});