5palow
Last Updated: February 25, 2016
·
7.385K
· posbo

Mocking Backbone.Model fetch() requests with Sinon.fakeServer

Sometimes it is useful to mock the response of an XHR call, either the backend API endpoints are not in place or some other reason. Sinon comes with a fakeServer, which can be used to mock the response for different requests. It's not too hard to setup

Firstly, we need to create a new fakeServer and define a response.

var server = sinon.fakeServer.create();

server.respondWith("GET", "/document/12345",
 [ 200, {"Content-Type":"application/json"},'[{ "name": "paul" }]' ]);

Secondly, we need to create a simple Backbone model that accepts an ID property and uses it to generate the XHR url.

var MyDocument = Backbone.Model.extend({
    url: function () {
        return '/document/'+ id;
    }
});

We then create an instance of our model and request data using fetch(), finally we respond with our fake server.

var myDoc = new MyDocument({ id: 12345 });

// Fire XHR request
myDoc.fetch();

// Respond to XHR request
server.respond();

Our model should now be populated with the test data

myDoc.get('name'); // paul

3 Responses
Add your response

10863

thanks for the comment but on the respondWith the last argument must be a String not an Object

server.respondWith("GET", "/document/12345",
[ 200, {"Content-Type":"application/json"}, JSON.stringify({"name":"paul" })]);

over 1 year ago ·
10875

Thanks Jorge, updated my example :)

over 1 year ago ·
18259

Once the backbone model calls its fetch, gets queued on the fakeServer, and the server responds, how does the model get updated?

over 1 year ago ·