【问题标题】:How to test subscribe in jasmine /angular/ karma如何在 jasmine /angular/ karma 中测试订阅
【发布时间】:2021-07-25 20:14:53
【问题描述】:

我正在为具有订阅和错误处理程序的方法的组件编写测试。 我的.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');
});

我的测试只测试第一部分。如何测试函数的其余部分,包括订阅和错误?

【问题讨论】:

    标签: angular unit-testing jasmine karma-jasmine


    【解决方案1】:

    您似乎缺少的只是监视 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
    
    

    【讨论】:

      【解决方案2】:

      你可以使用 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);
      }));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-07
        • 1970-01-01
        • 2019-04-16
        • 2018-01-31
        • 1970-01-01
        相关资源
        最近更新 更多