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
Written by Paul Osborne
Related protips
3 Responses
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" })]);
Thanks Jorge, updated my example :)
Once the backbone model calls its fetch, gets queued on the fakeServer, and the server responds, how does the model get updated?