toy
toy

Reputation: 12131

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

    }

Upvotes: 15

Views: 21743

Answers (6)

serv-inc
serv-inc

Reputation: 38147

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

Upvotes: 1

mcepl
mcepl

Reputation: 2786

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.

Upvotes: 39

Alvis
Alvis

Reputation: 3743

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

Upvotes: 5

taro
taro

Reputation: 719

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

Upvotes: 12

Andreas Köberle
Andreas Köberle

Reputation: 110892

As mention in the comments with SinonJS you can easily mock the XHR object / create a fake server.

Upvotes: 6

CBusBus
CBusBus

Reputation: 2359

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.

Upvotes: -1

Related Questions