javascript - Backbone Fetch 中的模拟 JSON 响应?

标签 javascript ajax json backbone.js model

我正在学习 Backbone 并想“模拟”模型中 .fetch() 调用的结果。我不想使用测试库或实际访问外部服务。

基本上我在我的模型中有一个设置,如果 this.options.mock === true,那么只需使用一个内部 JSON 对象作为获取的“结果”。否则,实际使用真正的 AJAX 请求访问 API。

但是,这似乎行不通。当我点击实际的 API(“真实”获取)时,我的 View 成功地呈现了模型数据,但每当我尝试传递虚假数据时却没有。

有没有办法在不引入像 Sinon 这样的测试库的情况下,在 Backbone 中伪造 Fetch 响应?

这是完整的模型(至少是它的相关部分)。基本上,该模型获取数据,并将其格式化为模板。然后拥有该模型的 View 将其呈现出来。

'use strict';
(function (app, $, Backbone) {

    app.Models.contentModel = Backbone.Model.extend({

        /**
         * Initializes model. Fetches data from API.
         * @param  {Object} options Configuration settings.
         */
        initialize: function (options) {
            var that = this;
            that.set({
                'template': options.template,
                'mock': options.mock || false
            });

            $.when(this.retrieveData()).then(function (data) {
                that.formatDataForTemplate(data);
            }, function () {
                console.error('failed!');
            });
        },

        retrieveData: function () {

            var that = this, deferred = $.Deferred();

            if (typeof fbs_settings !== 'undefined' && fbs_settings.preview === 'true') {
                deferred.resolve(fbs_settings.data);
            }
            else if (that.get('mock')) {
                console.info('in mock block');

                var mock = {
                  'title': 'Test Title',
                  'description': 'test description',
                  'position': 1,
                  'byline': 'Author'
                };

                deferred.resolve(mock);
            }
            else {
                // hit API like normal.
                console.info('in ajax block');
                that.fetch({
                    success: function (collection, response) {
                        deferred.resolve(response.promotedContent.contentPositions[0]);
                    },
                    error: function(collection, response) {
                        console.error('error: fetch failed for contentModel.');
                        deferred.resolve();
                    }
                });
            }
            return deferred.promise();
        },

        /**
         * Formats data on a per-template basis.
         * @return {[type]} [description]
         */
        formatDataForTemplate: function (data) {
            if (this.get('template') === 'welcomead_default') {
                this.set({
                    'title': data.title,
                    'description': data.description,
                    'byline': data.author
                });

            }
            // trigger the data formatted event for the view to render.
            this.trigger('dataFormatted');
        }
    });
})(window.app, window.jQuery, window.Backbone);

来自 View (ContentView)的相关位:

this.model = new app.Models.contentModel({template: this.templateName});
this.listenTo(this.model, 'dataFormatted', this.render);

是不是数据设置的太快了,监听器还没设置好?

最佳答案

您可以像这样覆盖获取函数。

var MockedModel = Backbone.Model.extend({
  initialize: function(attr, options) {
    if (options.mock) {
      this.fetch = this.fakeFetch;
    }
  },
  url: 'http://someUrlThatWIllNeverBeCalled.com',
  fakeFetch: function(options) {
    var self = this
    this.set({
      'title': 'Test Title',
      'description': 'test description',
      'position': 1,
      'byline': 'Author'
    });

    if (typeof options.success === 'function') {
      options.success(self, {}, {})
    }
  }
});
var mockedModel = new MockedModel(null, {
  mock: true
})
mockedModel.fetch({
  success: function(model, xhr) {
    alert(model.get('title'));
  }
});
    <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - Backbone Fetch 中的模拟 JSON 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31859830/

相关文章:

json - 将元数据添加到 jsTree

jquery - WCF Ajax 调用不适用于 Jquery $.ajax

javascript - 如何在多个Jquery Get函数中等待

javascript - 使用 jquery 更改 wordpress 主题中的一些 css 属性

非 200 响应情况下的 javascript 图像 onError

javascript - 在 Flask 中完成调查后重定向用户不起作用

jquery - 如何知道所有ajax调用何时完成

javascript - 检查对象中的 "constructor"键的奇怪 javascript 行为

javascript - AJAX 不适用于 jQuery

windows - Zend : . htaccess 现在不能在 Windows 上运行如何继续我的项目?