【问题标题】:Sinonjs: how to mock Backbone fetchSinonjs:如何模拟 Backbone fetch
【发布时间】:2018-03-24 06:50:03
【问题描述】:

我使用Backbone,在accountsView.js中有如下功能:

loadData: function () {

            this.accountsCollection.fetch()
                .done(_.bind(this.loadDefaultAccounts, this))
                .fail(_.bind(this._accountsLoadFailed, this));
        },

在 qunit 测试中,我试图像这样模拟它:

sandbox.stub(Backbone.Collection.prototype, "fetch").yieldsTo("done", {});

但在运行测试时出现以下错误:

"fetch 预期会屈服于 'done',但没有对象具有这样的属性 已通过。”

我错过了什么?

【问题讨论】:

  • .fetch 函数接受options 对象,您可以在其中传递successerror 回调以及context 以供使用。例如.fetch({context: this, success: this.loadDefaultAccounts});

标签: backbone.js sinon


【解决方案1】:

yieldsTo 在我看来是用来处理基于回调的代码。

要模拟 AJAX 请求,您应该设置一个 fake server 并执行类似的操作

this.server.respondWith("GET", "/some/article/comments.json",
        [200, { "Content-Type": "application/json" },
         '[{ "id": 12, "comment": "Hey there" }]']);

【讨论】:

    【解决方案2】:

    非常感谢您的提示。为了我的测试工作,视图中的函数应该是这样的:

    loadData: function () {
    
                this.accountsCollection.fetch({
                    success: _.bind(this.loadDefaultAccounts, this),
                    error: _.bind(this._accountsLoadFailed, this),
                });                
            },
    

    或者按照@TJ 的建议在测试中使用假服务器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-14
      • 2023-03-23
      • 2012-11-01
      相关资源
      最近更新 更多