I'm trying to write a test suite around my AjaxRequest class, but when I'm trying to inspect the request body I get this test failure
FAILED TESTS:
AjaxRequest
#POST
✖ attaches the body to the response
PhantomJS 1.9.8 (Mac OS X 0.0.0)
Expected Object({ example: [ 'text' ] }) to equal Object({ example: 'text' }).
Here's the relevant bit of the unit test:
req = new AjaxRequest().post('http://example.com')
.body({
example: 'text'
}).run();
And here's the run()
method where the ajax request is made
var options = {
url: this._url,
method: this._method,
type: 'json',
data: this._body
};
return when(reqwest(options));
I'm using reqwest to issue ajax requests.
Could someone point out why it's expecting ['text']
when the request sent 'text'
in the json body?
Thank you!
Changing the implementation of AjaxRequest solved the problem.
Here is the new implementation of run
using XMLHttpRequest
run () {
var req = new XMLHttpRequest();
req.open(this._method, this._url, true);
req.send(JSON.stringify(this._body));
return when.promise((resolve, reject) => {
req.onload = function() {
if (req.status < 400) {
var param = req.response;
try { param = JSON.parse(param) } catch (e) { };
resolve(param);
} else {
reject(new RequestError(req.statusText, req.status));
}
};
});
}
This not only gets rid of an extra library but also leaves more control over when to reject a request promise.