我有以下要进行单元测试的服务。我已经模拟了 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;
});