Last Updated: February 25, 2016
· magalhini

Testing $.ajax calls with Jasmine 2

A quick and easy way of implementing tests for your applications Ajax calls (assuming jQuery here, but it will work with pretty much everything else).

It involves spying on the original ajax method, creating a spied callback, and providing some fake data that will be expected using a resolved promise.

So, a very simple implementation of the method we want to test could be something like:

Async.prototype.fetch = function (cb) {
    .done(function (data) {

Here we're simply grabbing a URL and run a callback against the returned data.

As for the Jasmine test, here's a sample full implementation:

describe("Async", function () {
    it("should fetch from a server", function () {
        var async = new Async();

        // creating our spied callback
        var callback = jasmine.createSpy('callback');
        var data = [
              {x: 0,  y: 0},

        spyOn($, 'ajax').and.callFake(function (req) {
            var d = $.Deferred();
           // resolve using our mock data
            return d.promise();


        // grabbing the returned arguments from the spied call:
        var fakeData = callback.calls.mostRecent().args[0];

And there you have it.

Say Thanks