英文:
Angular unit test http call - test is splicing up the query param into query params
问题
使用Angular 12,我有这个服务,其中包含这个调用:
consumeGetPatientsToReconcile(query) {
  const host = this.appConfigService.apiBaseUrl;
  const url = `${host}/foo/bar`;
  const obs = this.http.get(
    url,
    { params: query }
  );
  return obs.pipe(tap((data) => this.reconcileMainService.setReconcileData(data)));
}
而且我有这个单元测试:
it('should consume patients reconcile api', () => {
  service.consumeGetPatientsToReconcile('page=1').subscribe((data) => {});
  const req = httpTestingController.expectOne('host/foo/bar');
  const foo = req.request.params.get('page');
  console.log(foo);
  httpTestingController.verify();
});
但在测试中,它正在拆分查询参数 page。
错误:期望匹配条件为 "匹配 URL: host/foo/bar" 的一个请求,但没有找到。接收到的请求为:GET host/foo/bar?0=p&1=a&2=g&3=e&4==&5=1。
而且,在 req.request.params.get('page') 中似乎缺少参数。
英文:
Using Angular 12, I have this service which has this call
    consumeGetPatientsToReconcile(query) {
      const host = this.appConfigService.apiBaseUrl;
      const url = `${host}/foo/bar`;
                          
      const obs = this.http.get(          
        url,
        { params: query }
      );
      return obs.pipe(tap((data) => this.reconcileMainService.setReconcileData(data) ));
    }
and I have this unit test
    it('should consume patients reconcile api', () => {
      service.consumeGetPatientsToReconcile('page=1').subscribe((data) => {});
      const req = httpTestingController.expectOne('host/foo/bar');
      const foo = req.request.params.get('page')
      console.log(foo);
  
      httpTestingController.verify();
    });
but in the test it is splicing up the query params page
> Error: Expected one matching request for criteria "Match URL: host/foo/bar", found none. Requests received are: GET host/foo/bar?0=p&1=a&2=g&3=e&4==&5=1.
Also, it seems the param is missing in req.request.params.get('page')
答案1
得分: 0
你不能直接将字符串作为 HttpClient.get 的 options 参数的 params 属性传递(或者一般的请求)。它需要一个 HttpParams 类型的对象,因此你需要创建一个。你的情况相当简单,所以你可以简单地这样做:
const obs = this.http.get(          
  url,
  { params: new HttpParams().set('page', '1') }
);
而对于更复杂的情况,你可以利用 HttpParamsOptions 实用程序,比如 fromObject。
总的来说,我建议更好地为你的代码添加类型,并且可能重新思考你的项目结构,因为返回一个被 tap 的 observable 的方法相当不寻常,不太合适。
英文:
You cannot pass directly a string as params property of options argument for HttpClient.get (or request in general).
It expects an object of type HttpParams, so you need to create one.
Your case is quite trivial so you can simply do
const obs = this.http.get(          
  url,
  { params: new HttpParams().set('page', '1') }
);
while for more complex situation, you can leverage HttpParamsOptions utilities like fromObject.
In general, I suggest to better type your code, and maybe rethink your project's structure, because that method returning a tapped observable is quite unusual and doesn't smell too nicely.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论