Test service call with success (), error () in jasmine
This is one of the functions of 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 am using to check when we call sendMeetingInvitation()
if it should call the success()
service call blockmeetingService.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 am getting this error which is not very 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 wrong here? I tried using mockedHttpPromise
. but the same result
source to share
The sendInvitations function expects the promise to return, so what you need to do is to defer and return it, like this:
- First of all you need to enter $ q: $q = $injector.get('$q');
-Create a deferral: deferred = $q.defer();
Your mockedHttpPromise function should look like this:
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 check the error block change deferred.resolve
todeferred.reject
source to share