Fake model answer in backbone.js

How can I fake a REST response in my st model, it really does not fit the service, but returns a fixed json?

If possible, show me a version that does this with an override of sync () and a version that overrides fetch (). I failed with both, so it will be a good education, as there is a difference between the two.

+6
source share
5 answers
Backbone.Model.extend({ fetch: function(){ var model = this; model.set({yourStatic: "Json Here"}); } } 

That should work. From the Backbone documentation:

fetch() : Resets the model state from the server by delegating to Backbone.sync

+9
source

If your question is about unit testing your code without the need for a real-time API, check out Sinon.JS . This helps mock all API server responses for testing purposes.

Here is an example from the Sinon docs that mocks the $ .ajax jQuery function:

 { setUp: function () { sinon.spy(jQuery, "ajax"); }, tearDown: function () { jQuery.ajax.restore(); // Unwraps the spy }, "test should inspect jQuery.getJSON usage of jQuery.ajax": function () { jQuery.getJSON("/some/resource"); assert(jQuery.ajax.calledOnce); assertEquals("/some/resource", jQuery.ajax.getCall(0).args[0].url); assertEquals("json", jQuery.ajax.getCall(0).args[0].dataType); } } 
+2
source

Take a look at the backbone-faux-server . This will allow you to process (and "fake" the response to any synchronization (selection, saving, etc.) for each model (or collection).

+2
source

Sinon.js is a good candidate, although if you want to simulate more than a few answers, it can be a lot of work in setting up headers, processing recording logic, etc.

Created on Sinon.js, FakeRest goes further and mimics the full REST API based on the JSON object — the entire -side client.

0
source

My code is like this

 // config const TEST_JSON = require('./test.json') const API_MAP = { testA: 'someroot' } const FAKE_API_MAP = { testA: TEST_JSON } // here model let BaseModel = Backbone.Model.extend({ url: function() { return `${HOST}${API_MAP[this.resourceName]}/` } }) let FakeModel = Backbone.Model.extend({ fetch: function(options) { return this.sync('', this, _.extend({}, options)); }, sync: function(method, model, options) { this.set(FAKE_API_MAP[this.resourceName], this.options) this.trigger('sync', this); }, }); // now it easy for switch them let modelA = new BaseModel({ resourceName: 'testA' }) modelA.fetch() let fakeModelA = new FakeModel({ resourceName: 'testA' }) fakeModelA.fetch() 
0
source

Source: https://habr.com/ru/post/918961/


All Articles