So you’ve just written a ton of javascript using backbone.js and decided you want to save yourself the pain of unexpected regressions so decide to use QUnit to write your tests but you want to mock the calls backbone.js makes to our API. Turns out its actually fairly easy, just use sinon.js.
First for any test where you want to call the pretend API you need to setup a fake server and prime it with a response. To do this place it all inside of your setup like so:
module("Backbone.Model can recieve data", {
setup: function () {
this.server = sinon.fakeServer.create();
this.server.respondWith("GET", "/v0/myApp/groups",
[200, { "Content-Type": "application/json" },
'{ "id": { "id": 1, "href": "/v0/myApp/1" }, "entity": { "id": 1, "title": "Example 1", "summary": "Test" } }']);
this.groups = new GroupCollection();
},
teardown: function () {
this.server.restore();
}
});
In line 2 we create the fake server, then on line 3 we tell that fake server to intercept everything going to “/v0/myApp/groups” using HTTP-GET
On line 4 we tell the server to respond with a 200 header and that it should set the MIME type to json.
Lines 5 and 6 then contain the actual JSON you want sending back to the backbone.js model.
Line 11 just tidies up for you.
So now you’ve got a fake server to pretend to be your API you now need to run fetch on your backbone.js models and respond via your fake server, always in that order. Always.
Then hey presto you’ve got a working mock for your backbone models. In the words of Garth and Wayne. Scha-wing.
Example of a test using the fake server to provide a model
test("Is backed by a model collection instance, which provides the data.", function () {
expect(2);
this.groups.fetch();
this.server.respond();
notEqual(this.groups, undefined);
equal(this.groups.length, 1);
});
So now we’ve got working tests we can push things a bit further. Wouldn’t it be nice to be able to run these on the build server after every checkin to make sure you’ve not been daft? Yes I hear you cry. Then all you need to do is whip out a bit of the old PhantomJS. I’ll leave it as an exercise to the reader but mostly it involves finding the ‘run-qunit.js’ in the PhantomJS examples and running it against your tests.