【问题标题】:Backbone Views - Mocha - Targeting events in collection.fetch success callback function骨干视图 - Mocha - 在 collection.fetch 成功回调函数中定位事件
【发布时间】:2016-02-17 12:18:36
【问题描述】:

onBeforeShow 函数中测试marionette compositeviewm 时,我正在执行带有success 回调的collection.fetch。然而,在回调中,我继续克隆我的集合并将事件附加到它。

现在我的问题是在测试这个视图时,我将如何定位我在successcollection.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


    【解决方案1】:

    您可以确保获取存根执行它的成功回调。类似的东西

    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。

    【讨论】:

    • 我曾尝试使用假服务器,但它仍然没有触发成功回调,即使我在服务器响应中返回了 200 OK。 fetch 存根只是 collection.prototype fetch 方法上的一个存根。我知道这不会触发回调。我将尝试将成功回调添加到存根本身,看看它是如何工作的。
    • 我再次查看了 fetch 参数并编辑了我的答案。
    • 我已经更新了我的问题。即使我存根我的 fetch 方法并让它返回一个成功函数,由于某种原因,这永远不会达到。可能是因为它在onBeforeShow 函数中?我已经尝试在测试服中手动调用onBeforeShow,但仍然没有达到成功回调。
    猜你喜欢
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多