Angular 单元测试的响应与 http 响应不同

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

大家好,我几乎是 Angular 的新手,我想为 AUTH 服务代码创建失败和成功场景,如下所示,但不知何故我的成功场景单元测试未通过。

    isAuthenticated(): Observable<any>{
    let token = String(localStorage.getItem('token'));
    return this.http.post<any>(`${environment.apiURL}/verify`,{ token: token }, {observe: 'response'})
      .pipe(
        map( (res:any) =>{
            if (res.body.user.imageURL) {
              res.user.imageURL = environment.hostURL + res.body.user.imageURL;
            }
            let user: User = res.body.user;
            this.userService.setCurrentUser(user)
            return of({ res: true , message: 'token is valid' })
        }),
        catchError(err=>{
          return of({ res: false , message: 'token is not valid' })
        })
      ) 
}

这是我的单元测试

    it('should return success  result', (done: DoneFn) => {
    const mockSuccessResponse = { res: true, message: 'token is valid' };
    httpClientSpy.post.and.returnValue(asyncData(mockSuccessResponse));
      authService.isAuthenticated().subscribe({
      next: res => {
        expect(res)
          .withContext('expected login result')
          .toEqual(mockSuccessResponse);
        done();
      },
      error: done.fail
    });
    expect(httpClientSpy.post.calls.count())
      .withContext('one call')
      .toBe(1);  
});

我得到的错误是

我将不胜感激任何帮助或建议

angular unit-testing karma-jasmine
1个回答
0
投票

实现这一目标的最佳方法是在

HttpClientTestModule
中使用
TestBed
,如下所示:

beforeEach(() => { 
  TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
      ],
      providers: []
    });
    httpMock = TestBed.inject(HttpTestingController);
});

之后,您必须使用

httpMock
来设置http调用的返回值:

  httpMock
    .expectOne({ method: "POST", url: `${environment.apiURL}/verify` })
    .flush(mockSuccessResponse);

避免出现类似错误的最佳方法

afterAll 抛出错误 就是不使用

done
而是将其称为异步,如下所示:

it("should do something", async() => {
  // arrange
  const functionToTest = 
       lastValueFrom(authService.isAuthenticated());

      httpMock
        .expectOne({ method: "POST", url: `${environment.apiURL}/verify` })
        .flush(mockSuccessResponse);

  // act
  parametre = await functionToTest;
      
  // assert
  expect(parametre[0]).toEqual({ res: true , message: 'token is valid' });
});
© www.soinside.com 2019 - 2024. All rights reserved.