Tri*_*ong 3 testing backbone.js jasmine
我有一个包含模型的视图.视图从模型中侦听事件,并在触发事件后执行操作.以下是我的代码
window.Category = Backbone.Model.extend({})
window.notesDialog = Backbone.View.extend({
initialize: function() {
this.model.bind("notesFetched", this.showNotes, this);
},
showNotes: function(notes) {
//do stuffs here
}
})
Run Code Online (Sandbox Code Playgroud)
我想用Jasmine测试这个,下面是我的测试(不起作用)
it("should show notes", function() {
var category = new Category;
var notes_dialog = new NotesDialog({model: category})
spyOn(notes_dialog, "showNotes");
category.trigger("notesFetched", "[]");
expect(notes_dialog.showNotes).toHaveBeenCalledWith("[]");
})
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么上述测试不起作用?我得到的错误是"预期的间谍showNotes已被['[]'调用,但它从未被调用过."
我正在做一些类似于我有视图的事情,但除非我将它添加到原型中,并且在创建视图实例之前,否则我无法让间谍正常工作.
这是最终对我有用的:
view = Backbone.View.extend({
initialize: function(){
this.collection.bind("change", this.onChange, this);
},
...
onChange: function(){
console.log("Called...");
}
});
Run Code Online (Sandbox Code Playgroud)
describe("Test Event", function(){
it("Should spy on change event", function(){
var spy = spyOn(view.prototype, 'onChange').andCallThrough()
var v = new view( {collection: some_collection });
// Trigger the change event
some_collection.set();
expect(spy).toHaveBeenCalled()
});
});
Run Code Online (Sandbox Code Playgroud)
我会最初测试toHaveBeenCalled()期望并toHaveBeenCalledWith()在你完成工作后改为...
2013年5月6日更新:已更改update()为set()