当实际请求嵌套在Promise中时,HttpTestingController ExpectOne无法正常工作 [英] HttpTestingController expectOne not working when actual request is nested within a promise

查看:184
本文介绍了当实际请求嵌套在Promise中时,HttpTestingController ExpectOne无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图对一个服务进行单元测试,该服务从另一个服务获取一个值(返回一个Promise),然后执行http GET请求.

I am trying to unit test a service which gets a value from another service (returns a Promise) then execute http GET request.

我正在使用@ angular/common/http/testing中的HttpTestingController来模拟http请求.这是测试和生产代码:

I am using HttpTestingController from @angular/common/http/testing to mock the http request. Here is the test and prod code :

tested.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();    
}));

tested.service.ts

async get<T>(endpoint: string): Promise<T> {
  const baseUrl = await this.parametresService.getBaseUrl();
  return this.http.get<T>(`${baseUrl.valeur}${endpoint}`).toPromise();
}

似乎无法以这种方式嘲笑嵌套在Promise中的http请求.但这也许是我的误会.

It seems that a http request nested within a promise cannot be mocked that way. But maybe it's a misunderstanding from me.

推荐答案

对我来说,使用fakeAsync测试区确实有效.在那里,您可以使用tick()函数,直到所有的承诺都得到解决,然后再继续测试.问题是您不能在fakeAsync区域中发出任何XHR请求,但是对于HttpClientTestingModule来说,它对我来说很好用.

For me it worked, to use the fakeAsync testzone. There you have the tick() function which waits until all promises are resolved and continues your test afterwards. The Problem is that you can't make any XHR request in the fakeAsync Zone, but it worked fine for me with the 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();    
}));

这篇关于当实际请求嵌套在Promise中时,HttpTestingController ExpectOne无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆