【问题标题】:Trying to subscribe to a http call in test file, and i need to assert the observerable in my test尝试订阅测试文件中的 http 调用,我需要在测试中声明可观察者
【发布时间】:2020-05-23 08:26:00
【问题描述】:

我需要在我的测试中进行 HTTP 调用,并且我需要验证我的可观察性。

当我调试代码时,HTTP 调用在服务中被调用,但在我的测试中,它失败并说 http 是 undefined,但在调试时我能够在控制台中看到 http 观察结果。

          //service.ts file 
         //imports modles goes here 



  export class DataService {
      private api = this.configService.config.apiUrl;

  constructor(private http: HttpClient,
        private configService: AppConfigService,
        private errorService: ErrorService) 
          { 
          }
          public getCustomerList(): Observable<IUserResponse> {
                     return this.http.get<IUserResponse>`${this.api}/v1/getusers/users`);
      }

    }


 my test file serviec.specs.ts

  describe('OnboardingService', () => {
      beforeEach(() => {

     const httpClient = new HttpClient(new HttpXhrBackend({ build: () => new XMLHttpRequest() }));

    appConfigService= new AppConfigService(httpClient);

    appConfigService.config = { apiUrl:"https://test-test-getuser.json"}

    erroService = new ErrorService();

   service = new Dataservice(httpClient, appConfigService,erroService);
   it('should return an Observable<Iuser[]>', done => {

               service.getCustomerList().subscribe(response => {
          expect(response.users).toBeGreaterThan(0);
          done();
        });


    });
})

【问题讨论】:

  • 我猜this.http.get('{this.apiurl}/v1/getuser')有问题,应该是this.http.get('${this.apiurl} /v1/getuser')
  • 你有外部日志语句吗?喜欢console.log(this.http.get('{this.apiurl}/v1/getuser').subscribe((response)=&gt;{console.log(response.user)}))?您需要显示更多代码。请发布进行此调用的函数。
  • 你能执行这一行 this.http.get('{this.apiurl}/v1/getuser').subscribe(console.log) 并发送控制台打印的内容吗?
  • 需要进一步了解该问题以帮助解决它

标签: javascript node.js angular angular6


【解决方案1】:

试试这个

this.http.get(`${this.apiurl}/v1/getuser`).subscribe((response)=>{console.log(response.user)})

【讨论】:

    【解决方案2】:

    灰色右箭头显示您要执行的代码。下面的左灰色箭头显示了执行的结果。控制台日志在开发工具中没有箭头。

    执行.subscribe() 的结果是一个订阅者,您可以在屏幕截图中看到。您的代码不会执行您传递给.subscribe() 的函数。

    所以你的问题可能与你的端点有关。检查开发工具中的网络选项卡。

    【讨论】:

      猜你喜欢
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      • 2018-08-31
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多