How can I test the onreadystatechange on XMLHttpRequest or pure Javascript AJAX without jQuery? I\'m doing this because I\'m developing Firefox extension. I guess I have to use
Jasmine has its own Ajax mock library called ajax.js.
Provided by jasmine-ajax. To mock for a single spec use withMock
:
it("allows use in a single spec", function() { var doneFn = jasmine.createSpy('success'); jasmine.Ajax.withMock(function() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(args) { if (this.readyState == this.DONE) { doneFn(this.responseText); } }; xhr.open("GET", "/some/cool/url"); xhr.send(); expect(doneFn).not.toHaveBeenCalled(); jasmine.Ajax.requests.mostRecent().respondWith({ "status": 200, "responseText": 'in spec response' }); expect(doneFn).toHaveBeenCalledWith('in spec response'); }); });
The response is only sent when you use respondWith
. Just download the file, and add as a src
to your SpecRunner.html
. Example usage at https://github.com/serv-inc/JSGuardian (see the test folder).
As mention in the comments with SinonJS you can easily mock the XHR object / create a fake server.
And what about this one?
beforeEach(function() {
// spyOn(XMLHttpRequest.prototype, 'open').andCallThrough(); // Jasmine 1.x
spyOn(XMLHttpRequest.prototype, 'open').and.callThrough(); // Jasmine 2.x
spyOn(XMLHttpRequest.prototype, 'send');
});
...
it("should call proper YQL! API", function() {
podcast.load_feed('http://www.faif.us/feeds/cast-ogg/');
expect(XMLHttpRequest.prototype.open).toHaveBeenCalled();
});
Pure Jasmine without need to use any external library.
You can test it in such manner
it("should make XHR request", function() {
// arrange
var xhr = {
open: jasmine.createSpy('open')
};
XMLHttpRequest = jasmine.createSpy('XMLHttpRequest');
XMLHttpRequest.and.callFake(function () {
return xhr;
});
// act
submit();
// assert
expect(xhr.open).toHaveBeenCalled();
});
As per the facsimile of your code below you will likely be able to inject console.log() with the status code and status text.
This will help you identify any http errors. Speculatively I'd say the status will return 404.
submit : function() {
var url = window.arguments[0];
var request = new XMLHttpRequest();
request.open("POST", 'http://'+this.host+'/doSomething', true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send("param="+param+"&emotions="+this.getParams());
request.onreadystatechange = function() {
console.log(this.status+ " - "+ this.statusText);
};
}
An alternative to this would be to look at the request header / response within the firebug console. Which is a good point: If you're not using firebug or chrome dev tools you should change the console.log() call to something that appends the string to a document object do not use an alert() call.
How do I verify jQuery AJAX events with Jasmine?. A similar answer that implements Jasmine.