【发布时间】:2016-02-17 12:18:36
【问题描述】:
在onBeforeShow 函数中测试marionette compositeviewm 时,我正在执行带有success 回调的collection.fetch。然而,在回调中,我继续克隆我的集合并将事件附加到它。
现在我的问题是在测试这个视图时,我将如何定位我在success 的collection.fetch 回调中设置的各种事件/函数调用?
是否有可能,或者不是简单地无法进行代码重构的情况?
如果我在checkEmptyState 上设置sinon spy,然后在我为测试创建的集合中设置add 模型,则spy 不会被触发,这是有道理的,因为我已将@987654331 存根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!")}
}
});
我的stub 中的success 回调永远不会到达。
【问题讨论】:
标签: unit-testing backbone.js mocha.js sinon