My QUnit test case is focused on checking the posted data sent via a JQuery ajax request:
test("ajax tests", function () {
var xhr = sinon.useFakeXMLHttpRequest();
var requests = sinon.requests = [];
xhr.onCreate = function (request) {
requests.push(request);
};
var callback = sinon.spy();
var mockData = {mockData: "dummy content"}
$.ajax('/some/article', { success: callback, data: mockData, method: 'post' });
equal(sinon.requests.length, 1);
equal(sinon.requests[0].url, "/some/article");
equal(JSON.parse(sinon.requests[0].requestBody).mockData, mockData)
});
The issue arises when trying to parse the data as JSON due to the format of the request body being: mockdata=dummy+content
The encoding of the data, with spaces replaced by the + symbol, makes decoding and subsequent JSON parsing challenging.
The ultimate aim is to dynamically validate the request data using the fake XHR object instead of mocking the jQuery post or ajax methods. This approach ensures unit tests don't fail when switching between AJAX request implementations.
Anyone encountered similar challenges?
References:
Example of the code above: http://jsfiddle.net/ZGrTK/66/
An article illustrating the desired outcome:
(The code seems to have issues for some users, potentially related to backbone.js. My lack of experience with that framework might be a factor.)