这是我要测试的控制器功能.
saveItem = (): void => { this.updateItem(); this.loadingDialogService.showIndicator("Saving Item"); this._editItemService.updateItem(this.item).then((updatedItem: Item) => { this.loadingDialogService.cancelDialog(); this.goToMainView(); }).catch(() => { this.loadingDialogService.showErrorDialog("Failed to Save Item"); //this._log.error("Error CallingItemService"); }); }
这是我的测试:
it("should call method saveItem",() => { spyOn(controller,'updateItem'); spyOn(loadingDialogService,'showIndicator'); spyOn(editItemService,'updateItem').and.callFake(() => { let result: Item deferred.resolve(result); return deferred.promise; }); spyOn(loadingDialogService,'cancelDialog'); spyOn(controller,'goToMainView'); controller.saveItem(); expect(controller.updateItem).toHaveBeenCalled(); expect(loadingDialogService.showIndicator).toHaveBeenCalled(); expect(_editItemService.updateItem).toHaveBeenCalled(); expect(loadingDialogService.cancelDialog).toHaveBeenCalled(); expect(controller.goToMainView).toHaveBeenCalled(); });
测试在最后两次预期失败,抛出错误说
Expected spy cancelDialog to have been called.
Expected spy goToMainView to have been called.
解决方法
您有解决的承诺,因此您需要在函数调用之后但在测试之前运行摘要循环.
it("should call method saveItem",() => { spyOn(controller,'updateItem'); spyOn(loadingDialogService,'showIndicator'); spyOn(editItemService,'updateItem').and.callFake(() => { let result: Item deferred.resolve(result); return deferred.promise; }); spyOn(loadingDialogService,'cancelDialog'); spyOn(controller,'goToMainView'); controller.saveItem(); $scope.$digest(); expect(controller.updateItem).toHaveBeenCalled(); expect(loadingDialogService.showIndicator).toHaveBeenCalled(); expect(_editItemService.updateItem).toHaveBeenCalled(); expect(loadingDialogService.cancelDialog).toHaveBeenCalled(); expect(controller.goToMainView).toHaveBeenCalled(); });
话虽如此,你的测试后来会引发你的问题,因为它有5个断言(expect()s).当一个人失败时,你将不得不浪费时间搞清楚它是哪一个.坚持每次测试一次断言(OAPT.)这应该是5次测试,每次都有一个断言.这样,当某些事情失败时,你就会知道它是什么.