117

I am trying to use Jasmine to write some BDD specs for basic jQuery AJAX requests. I am currently using Jasmine in standalone mode (i.e. through SpecRunner.html). I have configured SpecRunner to load jquery and other .js files. Any ideas why the following doesn't work? has_returned does not become true, even thought the "yuppi!" alert shows up fine.

describe("A jQuery ajax request should be able to fetch...", function() {

  it("an XML file from the filesystem", function() {
    $.ajax_get_xml_request = { has_returned : false };  
    // initiating the AJAX request
    $.ajax({ type: "GET", url: "addressbook_files/addressbookxml.xml", dataType: "xml",
             success: function(xml) { alert("yuppi!"); $.ajax_get_xml_request.has_returned = true; } }); 
    // waiting for has_returned to become true (timeout: 3s)
    waitsFor(function() { $.ajax_get_xml_request.has_returned; }, "the JQuery AJAX GET to return", 3000);
    // TODO: other tests might check size of XML file, whether it is valid XML
    expect($.ajax_get_xml_request.has_returned).toEqual(true);
  }); 

});

How do I test that the callback has been called? Any pointers to blogs/material related to testing async jQuery with Jasmine will be greatly appreciated.

Parag Tyagi
  • 8,780
  • 3
  • 42
  • 47
mnacos
  • 1,195
  • 2
  • 8
  • 8

6 Answers6

235

I guess there are two types of tests you can do:

  1. Unit tests that fake the AJAX request (using Jasmine's spies), enabling you to test all of your code that runs just before the AJAX request, and just afterwards. You can even use Jasmine to fake a response from the server. These tests would be faster - and they would not need to handle asynchronous behaviour - since there isn't any real AJAX going on.
  2. Integration tests that perform real AJAX requests. These would need to be asynchronous.

Jasmine can help you do both kinds of tests.

Here is a sample of how you can fake the AJAX request, and then write a unit test to verify that the faked AJAX request was going to the correct URL:

it("should make an AJAX request to the correct URL", function() {
    spyOn($, "ajax");
    getProduct(123);
    expect($.ajax.mostRecentCall.args[0]["url"]).toEqual("/products/123");
});

function getProduct(id) {
    $.ajax({
        type: "GET",
        url: "/products/" + id,
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
}

For Jasmine 2.0 use instead:

expect($.ajax.calls.mostRecent().args[0]["url"]).toEqual("/products/123");

as noted in this answer

Here is a similar unit test that verifies your callback was executed, upon an AJAX request completing successfully:

it("should execute the callback function on success", function () {
    spyOn($, "ajax").andCallFake(function(options) {
        options.success();
    });
    var callback = jasmine.createSpy();
    getProduct(123, callback);
    expect(callback).toHaveBeenCalled();
});

function getProduct(id, callback) {
    $.ajax({
        type: "GET",
        url: "/products/" + id,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: callback
    });
}

For Jasmine 2.0 use instead:

spyOn($, "ajax").and.callFake(function(options) {

as noted in this answer

Finally, you have hinted elsewhere that you might want to write integration tests that make real AJAX requests - for integration purposes. This can be done using Jasmine's asyncronous features: waits(), waitsFor() and runs():

it("should make a real AJAX request", function () {
    var callback = jasmine.createSpy();
    getProduct(123, callback);
    waitsFor(function() {
        return callback.callCount > 0;
    });
    runs(function() {
        expect(callback).toHaveBeenCalled();
    });
});

function getProduct(id, callback) {
    $.ajax({
        type: "GET",
        url: "data.json",
        contentType: "application/json; charset=utf-8"
        dataType: "json",
        success: callback
    });
}
Community
  • 1
  • 1
Alex York
  • 5,392
  • 3
  • 31
  • 27
  • +1 Alex great answer. Actually I faced a similar issue for which I have opened a question [Test Ajax request using the Deferred object](http://stackoverflow.com/questions/12080087/test-ajax-request-using-the-deferred-object). Could you take a look? thanks. – Lorraine Bernard Aug 22 '12 at 20:12
  • 12
    I really wish your answer was part of the official documentation for Jasmine. Very clear answer to a problem that has been killing me for a few days. – Darren Newton Sep 28 '12 at 18:30
  • 4
    This answer should really be marked as the official answer to this question. – Thomas Amar Jun 20 '13 at 06:44
  • It's a great answer, but it doesn't quite work for testing functions that make calls to functions that fire AJAX requests. Is there a good suggestion for pushing it out a level of nested functions without firing the AJAX request? I also have a question out about this at http://stackoverflow.com/questions/31975928/how-do-i-test-a-function-that-calls-an-ajax-function-without-firing-it-using-jas. Thanks, C§ – CSS Aug 12 '15 at 21:51
  • 1
    The current way to get the most recent call information is $.ajax.calls.mostRecent() – camiblanch Aug 14 '15 at 20:24
  • 1
    How would you implement that for plain JS ajax? – Watchmaker Nov 04 '16 at 12:46
13

Look at the jasmine-ajax project: http://github.com/pivotal/jasmine-ajax.

It's a drop-in helper that (for either jQuery or Prototype.js) stubs at the XHR layer so that requests never go out. You can then expect all you want about the request.

Then it lets you provide fixture responses for all your cases and then write tests for each response that you want: success, failure, unauthorized, etc.

It takes Ajax calls out of the realm of asynchronous tests and provides you a lot of flexibility for testing how your actual response handlers should work.

user533109
  • 141
  • 3
  • Thanks @jasminebdd, the jasmine-ajax project looks like the way to go for testing my js code. But what if I wanted to test with actual requests to the server, e.g. for connectivity/integration tests? – mnacos Jan 14 '11 at 12:38
  • 2
    @mnacos jasmine-ajax is mostly useful for unit testing in which case you specifically want to avoid the call to the server. If you're doing integration tests, this is probably not what you want and should be designed as a separate test strategy. – Sebastien Martin Apr 13 '12 at 15:37
7

here is a simple example test suite for an app js like this

var app = {
               fire: function(url, sfn, efn) {
                   $.ajax({
                       url:url,
                       success:sfn,
                       error:efn
                   });
                }
         };

a sample test suite, which will call callback based on url regexp

describe("ajax calls returns", function() {
 var successFn, errorFn;
 beforeEach(function () {
    successFn = jasmine.createSpy("successFn");
    errorFn = jasmine.createSpy("errorFn");
    jQuery.ajax = spyOn(jQuery, "ajax").andCallFake(
      function (options) {
          if(/.*success.*/.test(options.url)) {
              options.success();
          } else {
              options.error();
          }
      }
    );
 });

 it("success", function () {
     app.fire("success/url", successFn, errorFn);
     expect(successFn).toHaveBeenCalled();
 });

 it("error response", function () {
     app.fire("error/url", successFn, errorFn);
     expect(errorFn).toHaveBeenCalled();
 });
});
skipy
  • 4,032
  • 2
  • 23
  • 19
  • Thanks dude. This example helped me a lot! Just note that if you are using Jasmine > 2.0 the syntax for andCallFake is spyOn(jQuery, "ajax").and.callFake( /* your function */ ); – João Paulo Motta Mar 12 '15 at 00:10
  • Not sure if this is a version issue but I got an error on `.andCallFake`, used `.and.callFake` instead. Thanks. – O.O Feb 13 '19 at 14:21
5

When I specify ajax code with Jasmine, I solve the problem by spying on whatever depended-on function initiates the remote call (like, say, $.get or $ajax). Then I retrieve the callbacks set on it and test them discretely.

Here's an example I gisted recently:

https://gist.github.com/946704

Justin Searls
  • 4,789
  • 4
  • 45
  • 56
0

Try jqueryspy.com It provides an elegant jquery like syntax to describe your tests and allows callbacks to test after the ajax has complete. Its great for integration testing and you can configure maximum ajax wait times in seconds or milleseconds.

0

I feel like I need to provide a more up-to-date answer since Jasmine is now at version 2.4 and a few functions have changed from the version 2.0.

So, to verify that a callback function has been called within your AJAX request, you need to create a spy, add a callFake function to it then use the spy as your callback function. Here's how it goes:

describe("when you make a jQuery AJAX request", function()
{
    it("should get the content of an XML file", function(done)
    {
        var success = jasmine.createSpy('success');
        var error = jasmine.createSpy('error');

        success.and.callFake(function(xml_content)
        {
            expect(success).toHaveBeenCalled();

            // you can even do more tests with xml_content which is
            // the data returned by the success function of your AJAX call

            done(); // we're done, Jasmine can run the specs now
        });

        error.and.callFake(function()
        {
            // this will fail since success has not been called
            expect(success).toHaveBeenCalled();

            // If you are happy about the fact that error has been called,
            // don't make it fail by using expect(error).toHaveBeenCalled();

            done(); // we're done
        });

        jQuery.ajax({
            type : "GET",
            url : "addressbook_files/addressbookxml.xml",
            dataType : "xml",
            success : success,
            error : error
        });
    });
});

I've done the trick for the success function as well as the error function to make sure that Jasmine will run the specs as soon as possible even if your AJAX returns an error.

If you don't specify an error function and your AJAX returns an error, you will have to wait 5 seconds (default timeout interval) until Jasmine throws an error Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.. You can also specify your own timeout like this:

it("should get the content of an XML file", function(done)
{
    // your code
},
10000); // 10 seconds
pmrotule
  • 9,065
  • 4
  • 50
  • 58