Search code examples
angulartypescriptunit-testingjasmineangular-httpclient

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


I have converted my HttpClient.Post method to a promise and returning a value from it.

Following is the code snippet

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;
}

everything is working as expected but now I'm trying to write Unit test case for the same, but I'm getting nowhere.

Following is the code that I have tried

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

and following is my test block

  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);
  })

I'm new to angular testing , so i'm not sure what i'm doing wrong


Solution

  • I got it resolved following is the solution i have done

      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);
      })