我正在尝试对从另一个服务获取值(返回 Promise)的服务进行单元测试,然后执行 http GET 请求。
我正在使用来自@angular/common/http/testing 的 HttpTestingController 来模拟 http 请求。这是测试和生产代码:
测试.service.spec.ts
it('should get base url from indexedDb then execute http get request', (async () => {
fakeParametresService.getBaseUrl.and.returnValue(Promise.resolve({valeur: 'http://host:port'}));
testedService.get<any>('/endpoint').then((response: any) => {
expect(response.key).toBe('value');
});
await http.expectOne('http://host:port/endpoint').flush({key: 'value'});
http.verify();
}));
Run Code Online (Sandbox Code Playgroud)
测试服务.ts
async get<T>(endpoint: string): Promise<T> {
const baseUrl = await this.parametresService.getBaseUrl();
return this.http.get<T>(`${baseUrl.valeur}${endpoint}`).toPromise();
}
Run Code Online (Sandbox Code Playgroud)
似乎无法以这种方式模拟嵌套在 Promise 中的 http 请求。但也许这是我的误解。
对我来说,使用测试区是有效的fakeAsync。在那里你有一个tick()函数,它等待所有的承诺都得到解决,然后继续你的测试。问题是你不能在fakeAsyncZone 中发出任何 XHR 请求,但它对我来说很好用HttpClientTestingModule.
it('should get base url from indexedDb then execute http get request', fakeAsync(() => {
fakeParametresService.getBaseUrl.and.returnValue(Promise.resolve({valeur: 'http://host:port'}));
testedService.get<any>('/endpoint').then((response: any) => {
expect(response.key).toBe('value');
});
// wait until all Promises are resolved
tick();
http.expectOne('http://host:port/endpoint').flush({key: 'value'});
http.verify();
}));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6514 次 |
| 最近记录: |