UIalpha
UIalpha

Reputation: 3

Jasmine mocking a external API function with a callback argument

I'm calling a external API method for a post method, but I'm not able to get it cover using jasmine.

I have already mocked the external API function using window object and created a function to mock the callback by returning some object. But nothing helps.

Javascript

function loadApi() {
  extAPI.load({
    email: 'testEmail.test.com'
  }, function(resultObject) {
     if(resultObject.approved) {
       // callback with result object - not able to cover this
     }
  });
}

Spec.js & Mock-ups

beforeEach(function() {
  function mockLoadCallback() {
            var object = {
              approved: false
            };

            return object;
        }
  widnow.extAPI = {
       load: function(object, Function) {
                    var deferred = $.Deferred();

                    deferred.resolve(mockLoadCallback);

                    return deferred.promise();
        }
  }

});

it('load the external API response', function() {
  var loadSpy = spyOn(extAPI, 'load');
  loadApi();
  expect(loadSpy).toHaveBeenCalled();
});

statements and logic in the load call back should be covered but not even calling after the spy. what I'm doing wrong here.

Upvotes: 0

Views: 979

Answers (1)

Andrew Eisenberg
Andrew Eisenberg

Reputation: 28757

You are missing .and.callThrough() after the call to spyOn`. Your test should look like this:

it('load the external API response', function() {
  var loadSpy = spyOn(extAPI, 'load').and.callThrough();
  loadApi();
  expect(loadSpy).toHaveBeenCalled();
});

The callThrough method ensures that after the spy is invoked, the spy delegates to the original behavior.

Upvotes: 0

Related Questions