Exploring Backbone and looking for a way to simulate the response of a .fetch()
call within a model without using a testing library or connecting to an external service.
If the setting in the model is this.options.mock === true
, I'd like to use an internal JSON object as the fetch result. Otherwise, make a real AJAX request to the API.
However, it's not working as expected. The view renders properly with data from the API (real fetch), but doesn't display anything when using fake data. Is there a way to mimic a Fetch response in Backbone without relying on tools like Sinon?
Here's a snippet of the model code that handles fetching data and preparing it for rendering in a template, followed by how the view utilizes this model:
'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!');
});
},
// Remaining model logic goes here
})(window.app, window.jQuery, window.Backbone);
Relevant bit from the view (ContentView):
this.model = new app.Models.contentModel({template: this.templateName});
this.listenTo(this.model, 'dataFormatted', this.render);
Could it be that the data is being set too quickly before the listener is fully set up?