angular - 如何在 Angular 6 中对 Http 删除进行单元测试?
问题描述
我想编写用于从网格中删除记录的单元测试。
下面是 delete.component.ts 文件,其中显示了 deleteRecord 方法
deleteRecord(id: string): void {
const result = confirm("Are you sure you want to delete record?");
if (result) {
this.deleteService.deleteRecord(id).subscribe(() => {
const index = this.gridDetails.findIndex
((i) => i.id === id);
this.gridDetails.splice(index, 1);
alert("Deleted successfully");
}, (error: ErrorResponse) => {
alert("Delete failed");
});
}}
下面是 delete.service.ts 文件
deleteRecord(id: string): Observable<void> {
return this.http.delete<void>('http:/xyz/server/api/blogs/' + id);}
下面是 delete.component.spec.ts 文件
it('should delete record from grid on click of ok', () => {
spyOn(component, 'deleteRecord').and.callThrough();
spyOn(window, 'confirm').and.returnValue(true);
component.deleteRecord(mockDeleteService.id);
expect(component.deleteRecord).toHaveBeenCalled();
});
it('should not delete Record from grid on click of cancel', () => {
spyOn(component, 'deleteRecord').and.callThrough();
spyOn(window, 'confirm').and.returnValue(false);
expect(component.deleteRecord).not.toHaveBeenCalled();
});
请帮助我编写/改进上述代码的单元测试