我正在为一个具有订阅和错误处理程序的方法的组件编写测试。我的.ts
文件有这个
public viewDetails(orderNumber, orderType, orderCompany, businessUnitDesc): void {
this.showingDetails = true;
this.detailsLoading = true;
this.spinnerMessage = 'Loading Details';
const ordDet = {
orderNumber,
orderType,
orderCompany
};
this.businessUnitDesc = businessUnitDesc;
this.http.post<OrderDetailsResponse>(this.orderDetailsUrl, ordDet).subscribe(data => {
this.detailJsonString = JSON.stringify(data);
this.orderDetails = data;
this.freightHandlingCodeDesc = this.modeOfTrnDesc = this.routeCodeDesc = '';
this.getDescForFreightHandlingCode(this.orderDetails.freightHandlingCode);
this.getDescForModeOfTrnsCode(this.orderDetails.modeofTrn);
this.getDescForRouteCode(this.orderDetails.routeCode);
this.stopDetailsLoading();
this.appInsightsService.logEvent('Order Details', {orderNumber});
},
error => {
this.detailsLoading = false;
this.appInsightsService.logException(error);
this.authService.viewStandardErrorMessage();
});
}
我已经尝试在.spec.ts
文件中测试它,像这样:
it ('should view details', () => {
component.viewDetails(1, 'a', 'b', 'c');
expect(component.showingDetails).toBe(true);
expect(component.detailsLoading).toBe(true);
expect(component.spinnerMessage).toBe('Loading Details');
});
我的测试只测试第一部分。我如何测试函数的其余部分,包括订阅和错误?
您可以使用fakeAsync以及flush()和tick()
it ('should set detailJsonString to the results string', fakeAsync(() => {
const mockDataObj = getMockData();
const httpSpy = TestBed.inject(HttpClient)
spyOn(httpSpy, 'post').and.returnValue(of(mockDataObj))
component.viewDetails(1, 'a', 'b', 'c');
flush(); // clear out any pending tasks in queue including observable magic
tick(); // simulate passage of time
const expectedString = JSON.stringify(mockDataObj);
expect(component.detailJsonString).toEqual(expectedString);
}));
您似乎错过了监视http请求以模拟响应。
const httpSpy = TestBed.inject(HttpClient)
spyOn(httpSpy, 'post').and.returnValue(of(MOCKDATA_GOES_HERE))
// call your method that calls the http request
// do your stuff