// uses sinon and jQueryJSFiddle: http://jsfiddle.net/stevenhollidge/crDCT/4/
var server = sinon.fakeServer.create();
server.respondWith([200, { "Content-Type": "application/json" }, '{"myData":3}']);
$.getJSON('some/url');
console.log(server.response);
server.restore();
// uses sinon and jquery
var xhr = sinon.useFakeXMLHttpRequest();
var requests = [];
xhr.onCreate = function (request) {
requests.push(request);
};
var responseData = '{"myData":3}';
$.getJSON('some/url', function(data) { console.log(data); });
requests[0].respond(200, { "Content-Type": "application/json" }, responseData);
console.log(requests[0].url);
xhr.restore();
JSFiddle: http://jsfiddle.net/stevenhollidge/crDCT/2/
An example combined with Jasmine to mock out the http call:
// uses jasmine, sinon and jQuery
describe("useFakeXMLHttpRequest", function() {
var xhr, requests;
beforeEach(function () {
xhr = sinon.useFakeXMLHttpRequest();
requests = [];
xhr.onCreate = function (request) {
requests.push(request);
};
},
afterEach: function () {
xhr.restore();
},
it('should be able to handle responses', function () {
var responseData = '{"myData":3}';
$.getJSON('some/url', function(data) { console.log(data); });
requests[0].respond(200, { "Content-Type": "application/json" }, responseData);
expect(requests[0].url).toBe('some/url');
}
}
No comments:
Post a Comment