我有以下服务,我想进行单元测试。我已经模拟了personService.deletePerson函数,并希望测试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();
}
......
这是我的考验。
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
});
});
有人能指出我正确的方向来测试这种情况吗?我意识到我可以删除deletePerson上的间谍,但是它不会孤立地测试这个服务。
感谢。
更新 我已尝试使用codemonkey建议的andCallFake,但我仍有问题。
spyOn(personService, 'deletePerson').andCallFake(function () {
def = q.defer();
def.resolve(true);
return def.promise;
});