Skip to content

Instantly share code, notes, and snippets.

@philfreo
Created December 18, 2012 05:19
Show Gist options
  • Save philfreo/4325280 to your computer and use it in GitHub Desktop.
Save philfreo/4325280 to your computer and use it in GitHub Desktop.
Test AJAX Request data with QUnit and Sinon.JS
module("Faking response data", {
setup: function () {
var testData = { foo: 'bar', name: 'phil' };
this.server = sinon.fakeServer.create();
this.server.respondWith("GET", "/api/testmodel/1", [200, { "Content-Type": "application/json" }, JSON.stringify(testData)]);
},
teardown: function () {
this.server.restore();
}
});
test("Fetching TestModel", function () {
var TestModel = Backbone.Model.extend({
url: function() { return '/api/testmodel' + (this.id ? '/'+this.id : ''); }
});
var model = new TestModel({ id: 1 });
model.fetch();
this.server.respond();
equal(model.get('foo'), 'bar', 'fetched model has expected attributes');
});
module('Test XHR Request Example', {
setup: function() {
this.requests = [];
this.xhr = sinon.useFakeXMLHttpRequest();
this.xhr.onCreate = $.proxy(function(xhr) {
this.requests.push(xhr);
}, this);
},
teardown: function() {
this.xhr.restore();
}
});
test('Creating TestModel', function() {
var TestModel = Backbone.Model.extend({
url: function() { return '/api/testmodel/'; }
});
var model = new TestModel({
'foo': 'bar',
'name': 'phil'
});
model.save();
var request = this.requests[0];
equal(request.method, 'POST', 'TestModel#save should send a POST');
equal(request.url, '/api/testmodel/', '... to /api/testmodel/ endpoint');
equal(JSON.parse(request.requestBody).name, 'phil', '... with valid SMTP json');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment