test service call with success () , error () in jasmine

2.1k views Asked by At

This is one of the functions in my controller

function sendMeetingInvitation(companyId, meetingId) {

  meetingService.sendInvitations(companyId, meetingId)
    .success(function() {
      $state.go('company.meeting.view', {}, {
        reload: true
      });
    })
    .error(function() {
      //more code for error handling
    });

}

Below is the test case I'm using to test when we call the sendMeetingInvitation(), whether it should invoke the to the success() block of the service call of meetingService.sendInvitations

describe('EditMeetingCtrl.sendMeetingInvitation()', function() {
  var $rootScope, scope, $controller, $q, companyService, meetingService;



  var mockedHttpPromise = {
    success: function() {}
  };

  beforeEach(angular.mock.module('MyApp'));


  beforeEach(angular.mock.inject(function(_$httpBackend_, _companyService_, _meetingService_) {
    $httpBackend = _$httpBackend_;
    companyService = _companyService_;
    meetingService = _meetingService_;
  }));

  beforeEach(inject(function($rootScope, $controller, _meetingService_) {
    scope = $rootScope.$new();
    createController = function() {
      return $controller('EditMeetingCtrl', {
        $scope: scope,
        meeting: {},
        meetingService: _meetingService_
      });
    };
    var controller = new createController();
  }));

  it("should should send invitations", function() {
    spyOn(meetingService, 'sendInvitations').and.returnValue(mockedHttpPromise);
    scope.sendMeetingInvitations(123456, 123456);
    expect(meetingService.sendInvitations).toHaveBeenCalledWith(123456, 123456);
  });


});

I get this error which is not really helpful .

PhantomJS 1.9.8 (Windows 8) In EditMeetingCtrl EditMeetingCtrl.sendMeetingInvitation() should should send invitations FAILED
TypeError: 'undefined' is not an object (near '...})...')

What am I doing here wrong? I tried my mockedHttpPromise to following . but same result

var mockedHttpPromise = {
  success: function() {},
  error: function() {}
};

1

There are 1 answers

0
Victor Oliveira On

The function sendInvitations expects to return a promise, so, what you need to do is to create a defer and return it, like this:

-First of all you need to inject $q: $q = $injector.get('$q');

-Create a defer: deferred = $q.defer();

Your function mockedHttpPromise, should look like:

function mockedHttpPromise() {
    deferred = $q.defer();
    return deferred.promise;
}

And inside your test:

  it("should should send invitations", function() {
    spyOn(meetingService, 'sendInvitations').and.returnValue(mockedHttpPromise);
    scope.sendMeetingInvitations(123456, 123456);
    deferred.resolve({});
    scope.$apply();
    expect(meetingService.sendInvitations).toHaveBeenCalledWith(123456, 123456);
  });

And to test error block, change deferred.resolve to deferred.reject