我已将HttpClient.Post方法转换为Promise,并从中返回值。
以下是代码段
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);
})
我是角度测试的新手,所以我不确定自己做错了什么
答案 0 :(得分:0)
我认为您应该将功能重构为特定于问题的。
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;
}
答案 1 :(得分:0)
我解决了以下问题,这是我已经完成的解决方案
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);
})