Created
December 18, 2012 05:19
-
-
Save philfreo/4325280 to your computer and use it in GitHub Desktop.
Test AJAX Request data with QUnit and Sinon.JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
http://philfreo.com/blog/how-to-unit-test-ajax-requests-with-qunit-and-sinon-js/