如何使用 await 测试转换为 Promise Angular 的 HttpClient

How to test HttpClient which is converted to a Promise Angular with await

我已将 HttpClient.Post 方法转换为承诺并从中返回一个值。

以下是代码片段

readonly API_URL = "www.xyz.api";

public async getAddress(
    id: string,
    name: string
): Promise < UserAddress[] > {
    const reqBody = {
        id, name
    }
    let addressDetails = null;
    await this.http
        .post<IUserAddressRes>(this.API_URL, reqBody)
        .toPromise()
        .then(res => {
            UserAddress = res.collection;
        })
        .catch(() => {
            UserAddress = null;
        });
    return UserAddress;
}

一切正常 但现在我正在尝试为此编写单元测试用例,但我一无所获。

以下是我试过的代码

 let httpMock: HttpTestingController; // inside describe
 
 httpMock = TestBed.get(HttpTestingController); // inside beforeEach
 
 TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
    });

下面是我的测试块

  it('should return null address', async () => {
    const req = httpMock.expectOne(service.API_URL);// this is failing with error as Expected one matching request for criteria "Match URL: www.xyz.api", found none.
    expect(req.request.method).toEqual('POST'); 
    req.flush(null);
    const response = await service.getAddress('id', 'name');
    expect(response).toEqual(null);
  })

我是 angular 测试的新手,所以我不确定我做错了什么

我认为你应该重构你的函数以针对特定问题。

readonly API_URL = "www.xyz.api";

public async getAddress(
    id: string,
    name: string
): Promise < UserAddress[] | null > {
    let addressDetails: UserAddress[] | null = null;
    const reqBody = {
        id, name
    }

    try {
      const res = await this.http
        .post<IUserAddressRes>(this.API_URL, reqBody)
        .toPromise();

      addressDetails = res.collection;
    } catch (err: any) {
      addressDetails = null;
    }

    return addressDetails;
}

我解决了下面是我已经完成的解决方案

  it('should return null address', async () => {
    const methodCall = service.getAddress('id', 'name');
    const req = httpMock.expectOne(service.API_URL);// this is failing with error as Expected one matching request for criteria "Match URL: www.xyz.api", found none.
    req.flush(null);
    const response = await methodCall;
    expect(req.request.method).toEqual('POST');
    expect(response).toEqual(null);
  })