Reputation: 11
I have the following service that I want to unit test. I have mocked out the personService.deletePerson function and want to test the code inside the promise.
treeApp.factory('userMediatorService', ['$q', '$dialog', 'personService', 'confirmationMessageService',
function ($q, $dialog, personService, confirmationMessageService) {
.......
deletePerson: function (personId) {
var self = this;
personService.deletePerson(personId).then(function (data) {
//how to test this?
self.closeAndRefresh();
confirmationMessageService.set('Person Deleted');
});
},
closeAndRefresh: function () {
this.closeModal();
}
......
This is my test.
beforeEach(inject(function ($injector) {
sut = $injector.get('userMediatorService');
personService = $injector.get('personService');
q = $injector.get('$q');
def = q.defer();
spyOn(personService, 'deletePerson').andReturn(
def.promise
);
}));
describe('when a person is deleted', function () {
it('should call the delete person service and close the modal', function () {
sut.deletePerson(123);
expect(personService.deletePerson).toHaveBeenCalledWith(123); //pass
expect(sut.closeAndRefresh).toHaveBeenCalled(); //fail
});
});
Can anyone point me in the right direction for testing this kind of scenario? I realise that I can remove the spy on deletePerson, but then it wouldn't test this service in isolation.
Thanks.
Update: I've tried using andCallFake as suggested by codemonkey and I still have the issue.
spyOn(personService, 'deletePerson').andCallFake(function () {
def = q.defer();
def.resolve(true);
return def.promise;
});
Upvotes: 1
Views: 224
Reputation: 5267
You probably want to use the callFake
on the spy rather than andReturn
. That will let you write a function that can resolve (or reject) the promise rather than just returning the promise.
Upvotes: 1