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 spies, but couldn't figure out how because my ajax won't return anything.
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() {
if(this.readyState == 4) {
// alert(this.responseText);
}
};
}
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();
});
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.
Jasmine has its own Ajax mock library called ajax.js.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With