角度服务内 if 语句的单元测试用例

问题描述 投票:0回答:1

我有一个服务(服务 1),它在内部从另一个服务(服务 2)返回数据。因此,在返回数据之前,我们在服务 1 中进行数据检查。

 `getuserImageUrl(Id: number): Observable<string> {
        return this.getUserDetailsAPI(Id)
          .pipe(
            map((userInfo: any) => {
              console.log(userInfo);
              let url = userInfo.url;
              if (url === undefined || url === null) {
                return '';
              }
              return url;
            })
          )
          .pipe(
            catchError((error) => {
              console.log(error);
              return '';
            })
          );
      }`

我已经尝试了以下方法,但在代码覆盖率中它说服务中的 if 块未被覆盖。如何在单元测试中覆盖这个 if 块

it('should provide null if image url is null', fakeAsync(() => {
    userServiceSpy.getUserDetailsAPI.and.returnValue(of(""));
    userService.getuserImageUrl(Id)
      .subscribe((data) => {        
        expect(userServiceSpy.getUserDetailsAPI).toHaveBeenCalled();
        expect(data).toEqual('');
      });

      const req1 = httpTestingController.expectOne(
        `myproject.com/getuserImageUrl/${Id}`
      );
      expect(req1.request.method).toEqual('GET');
        req1.flush("");
      
  }));
angular jasmine
1个回答
0
投票

积极场景

it('should provide url if image url is present', fakeAsync(() => {
    userServiceSpy.getUserDetailsAPI.and.returnValue(of({ url: 'test' }));
    userService.getuserImageUrl(Id)
      .subscribe((data) => {        
        expect(userServiceSpy.getUserDetailsAPI).toHaveBeenCalled();
        expect(data).toEqual('test');
      });

      const req1 = httpTestingController.expectOne(
        `myproject.com/getuserImageUrl/${Id}`
      );
      expect(req1.request.method).toEqual('GET');
        req1.flush("");
      
  }));

负面场景

it('should provide empty string when url is undefined', fakeAsync(() => {
    userServiceSpy.getUserDetailsAPI.and.returnValue(of({ url: undefined }));
    userService.getuserImageUrl(Id)
      .subscribe((data) => {        
        expect(userServiceSpy.getUserDetailsAPI).toHaveBeenCalled();
        expect(data).toEqual('');
      });

      const req1 = httpTestingController.expectOne(
        `myproject.com/getuserImageUrl/${Id}`
      );
      expect(req1.request.method).toEqual('GET');
        req1.flush("");
      
  }));
© www.soinside.com 2019 - 2024. All rights reserved.