这是我的 Controller 我想测试的功能。
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.
我猜这个测试不会执行 里面的函数然后 功能。有人能指出错误在哪里吗?
最佳答案
您有一个要解决的 promise ,因此您需要在函数调用之后但在测试之前运行摘要循环。
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 个测试,每个测试一个断言。这样,当某些事情失败时,您就会知道它是什么。
关于angularjs - 然后在里面调用 Angular Jasmine 测试函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35322555/