Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test XMLHttpRequest with Jasmine

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);
            }
        };

    }

like image 653
toy Avatar asked Jan 17 '12 20:01

toy


3 Answers

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(); 
});
like image 104
Alvis Avatar answered Sep 24 '22 03:09

Alvis


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.

like image 39
mcepl Avatar answered Oct 21 '22 21:10

mcepl


Jasmine has its own Ajax mock library called ajax.js.

like image 11
taro Avatar answered Oct 21 '22 23:10

taro