如何模拟成功调用delete API服务(它 Package 了Angular Http服务),并为成功删除场景返回Observable?它不会返回void。
dpiehjr41#
这是我的解决方案--特别是返回一个200的对象的部分,它足以模拟对api-service的调用,该调用返回Angular的httpService.delete的结果。
describe('ItemStoreService', () => { let service: ItemStoreService; let itemApiServiceSpy: SpyObj<ItemApiService>; let notifyServiceSpy: SpyObj<NotifyService>; let anItem: Item; beforeEach(() => { anItem = { id: 1, name: 'testName', }; itemApiServiceSpy = createSpyObj('ItemApiService', ['delete', 'loadActiveItems']); notifyServiceSpy = createSpyObj('NotifyService', ['notifyError', 'notifySuccess']); TestBed.configureTestingModule({ providers: [ { provide: ItemApiService, useValue: itemApiServiceSpy }, { provide: NotifyService, useValue: notifyServiceSpy }, ], }).compileComponents(); service = TestBed.inject(ItemStoreService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('delete should call notifyError on error ', () => { itemApiServiceSpy.delete.and.returnValue( throwError(() => { return { status: 500, message: 'testError' }; }) ); service.delete(anItem.id); expect(itemApiServiceSpy.delete).toHaveBeenCalledOnceWith(anItem.id); expect(notifyServiceSpy.notifySuccess).not.toHaveBeenCalled(); expect(notifyServiceSpy.notifyError).toHaveBeenCalledWith( 'A problem was encountered while deleting Non-Production Bottle Lot ' + anItem.id ); }); it('delete should call notifySuccess on success ', () => { let loadActiveItemsSpy = spyOn(service, 'loadActiveItems'); itemApiServiceSpy.delete.and.returnValue(of({ status: 200, message: 'deleted.' })); service.delete(anItem.id); expect(itemApiServiceSpy.delete).toHaveBeenCalledOnceWith(anItem.id); expect(notifyServiceSpy.notifyError).not.toHaveBeenCalled(); expect(loadActiveItemsSpy).toHaveBeenCalled(); expect(notifyServiceSpy.notifySuccess).toHaveBeenCalledWith('Non-Production Bottle Lot was deleted.'); }); });
1条答案
按热度按时间dpiehjr41#
这是我的解决方案--特别是返回一个200的对象的部分,它足以模拟对api-service的调用,该调用返回Angular的httpService.delete的结果。