在marionette compositeview
函数中测试onBeforeShow
m时,我正在使用collection.fetch
回调执行success
。然而,在回调中,我继续克隆我的集合并将事件附加到它。
现在我的问题是在测试此视图时,如何定位我在success
collection.fetch
回调中设置的各种事件/函数调用?
它是否可能或者是不是根本不能进行代码重构?
如果我在sinon spy
上设置了checkEmptyState
,然后add
将模型设置为我为测试创建的集合,则spy
不会被触发,这有意义< strong>我在fetch
函数中为集合创建了beforeEach
方法,以防止任何api调用。如果可能,哪种方法/设置能够在success
回调中测试代码?
例如:
onBeforeShow: function () {
var that = this;
this.fetch = this.collection.fetch({
success: function (collection, response, options) {
if (!response.length ) {
that.addEmptyPostsMessage();
}
that.stopListening(that.collection);
//Change collection property and re-apply events
that.collection = that.collection.clone(that.options.filterAttr, that.options.isFiltered);
that._initialEvents();
that.collection.reset(that.collection.filterItems(that.collection.models, that.options.filterAttr), {reset: true});
that.listenTo(that.collection, 'update', that.checkEmptyState);
},
reset: false,
remove: false
});
}
对于我的测试设置:
beforeEach(function () {
this.server = sinon.fakeServer.create();
this.server.autoRespond = true;
this.collectionFetchStub = sinon.stub(My.Collection.Items.prototype, 'fetch', function () {
return: {
success: function () {console.log("this is never called!")}
}
});
我的success
中的stub
回调永远不会到达。
答案 0 :(得分:0)
您可以确保获取存根执行它的成功回调。像
这样的东西var collection = [...],
response = 'ok';
this.collectionFetchStub = sinon.stub(My.Collection.Items.prototype, 'fetch', function (options) {
options.success(collection, response);
};
或者当使用sinon fakeserver而不是使用autoRespond时,你应该尝试
server.respondWith([200, { 'Content-Type': 'text/html', 'Content-Length': 2 }, collection_json_as_string]);
确保响应有效json。