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
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).