javascript - Sinon.js, QUnit, and Jquery. Attempting to verify posted data through FakeXMLHttpRequest -
i have following qunit test case, attempting verify posted data sent through 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 json.parse fails, because request body formatted as: mockdata=dummy+content
because of how data encoded (spaces replaced + symbol), makes decoding content, , subsequently making json parseable difficult.
the end goal dynamically verify request data, using fake xhr object. prefer on mocking jquery post or ajax methods. since if switch between implementations sending ajax requests, don't want unit tests fail.
has had luck this?
references:
demo of above code: http://jsfiddle.net/zgrtk/66/
an article demonstrated trying achieve: http://philfreo.com/blog/how-to-unit-test-ajax-requests-with-qunit-and-sinon-js/
(the code fails work me. deal backbone.js suspect. have no experience framework though.)
a couple comments on test:
- jquery
ajax(
) documentation says ifdata
parameter isn't string, converted query string using$.param()
. avoid conversion passing string. - the last assert compares
[object].mockdata
variable namedmockdata
. i'm guessing that's typo.
here's modified test (jsfiddle) passes:
test("ajax tests", function () { var xhr = sinon.usefakexmlhttprequest(), requests = [], mockuri = '/some/article', mockdata = { someproperty: "dummy content" }; xhr.oncreate = function (request) { requests.push(request); }; $.ajax(mockuri, { data: json.stringify(mockdata), type: 'post' }); equal(requests.length, 1); equal(requests[0].url, mockuri); equal(json.parse(requests[0].requestbody).someproperty, mockdata.someproperty); xhr.restore(); });
as article, didn't study code, seems work: jsfiddle.
Comments
Post a Comment