user3878988
user3878988

Reputation: 841

How to unit test jquery ajax calls using jasmine?

I have below ajax call code in my .js file and I want to write jasmine unit tests to bring coverage.

var promise = $.ajax({
                url: URL,
                type: 'GET'
               });
promise.done(function(data, status) {
       console.log("success");
});
promise.fail(function(status, error) {
       console.log("error");
});

I am able to write unit test case for $.ajax calls by stubbing/mocking data, but not able to write test case for .done and .fail methods. Is there anyway to write specs for .done and .fail methods.

Upvotes: 0

Views: 2423

Answers (2)

Winter Soldier
Winter Soldier

Reputation: 2685

  • You may invoke other functions from you success/fail handler to effectively mock the promise handlers.
  • Besides making the code easy to read, it also helps to debug and mock
  • Slava Ivanov's answer helps you with stubbing the appropriate callback and it uses the Jquery Deferred object

Here is how I slightly modified your question to suit mock behavior. See it in action here

var handler = {
  success: function(data) {
    console.log("success");
  },
  fail: function(data) {
    console.log("error");
  }
};
var testObj = {
  ajaxFunction: function() {
    var promise =
      $.ajax({
        url: 'abc',
        type: 'GET'
      });
    promise.done(function(data, status) {
      handler.success(data);
    });
    promise.fail(function(status, error) {
      handler.fail(error);
    });
  }
};

describe('test ajax', function() {
  it('test success', function() {
    spyOn(handler, 'success').and.callFake(function(e) {
      console.log("This is a spy call for success handler");
    });
    spyOn($, 'ajax').and.callFake(function(e) {
      return $.Deferred().resolve({
        'hurray': 'success'
      }).promise();
    });
    testObj.ajaxFunction();
    expect(handler.success).toHaveBeenCalled();
  });

  it('test failure', function() {
    spyOn(handler, 'fail').and.callFake(function(e) {
      console.log("This is a spy call for fail handler");
    });
    spyOn($, 'ajax').and.callFake(function(e) {
      return $.Deferred().reject({
        'alas': 'failure'
      }).promise();
    });
    testObj.ajaxFunction();
    expect(handler.fail).toHaveBeenCalled();
  });

});

Upvotes: 2

Slava Ivanov
Slava Ivanov

Reputation: 6912

To write test cases for .done and .fail methods you would need to create the Spy on $.ajax JQuery function, and call your own fake function where you would create Deferred object and resolve/reject it depends on your test. For example you code may looks like ...

// successful case
spyOn($, "ajax").and.callFake(function () {
    return $.Deferred().resolve(expected_data, expected_status).promise();
});

// failure case
spyOn($, "ajax").and.callFake(function () {
    return $.Deferred().reject(expected_status, expected_error).promise();
});

Upvotes: 0

Related Questions