【问题标题】:Angular: Testing HttpMock with multiple parameters expectOne() failsAngular:使用多个参数 expectOne() 测试 HttpMock 失败
【发布时间】:2020-05-05 11:23:05
【问题描述】:

我在 Angular 中有一项服务,它需要 3 个参数。 [我在使用 append() 时遇到了 HttpParams 的问题,所以我只是在构造函数中使用了 fromObject 参数。可能看起来很奇怪,但现在可以了。]

服务代码

getData(paramOne: string, paramTwo, string: paramThree: number): Observable<Object[]> {
  const obj = {};
  obj['p1'] = paramOne;
  obj['p2'] = paramTwo;
  obj['p3'] = paramThree;
  let params = new HttpParams({fromObject; obj});
  return this.httpClient.get<Object[]>('myurl', {params: params})
}

这行得通。在服务器端,我可以从请求中获取参数。没有问题。

但是,在使用 HttpMock() 的单元测试中,我确实遇到了问题。

// httpMock = new TestBed.get(HttpTestingController)

it('should get data', (done) => {
  const data = {};
 // populate simulated return data

 service.getData("param1", "param2", 3).subscribe(data => {
  // tests here
 });

 const req = httpMock.expectOne('myurl?p1=param1&p2=param2&p3=3');
 expect(req.request.method).toBe('GET');
 req.flush(data);
 httpMock.verify();
});

httpMock.epectOne() 调用失败

Expected one matching request for criteria "call to api", found none.

我已经用零和 1 个参数进行了尝试,并且该模式有效。我已经检查了拼写错误等等。令人讨厌的......我遗漏了什么,或者有什么方法可以仔细查看 URL 实际变成了什么?

【问题讨论】:

  • 什么是httpMock'类型,应该是HttpTestingController
  • 这是——对不起。以为就在里面。
  • 如果我删除回调中的done 参数(it('should get data', (done) =&gt; {) 那么你的测试对我有用
  • 如果我没记错的话,不能保证对象中的顺序正确吗?查看文档我假设我需要使用这些重载之一:angular.io/api/common/http/testing/…
  • @yurzui 它通过没有 done() 的原因是 b/c 它没有被运行。

标签: angular unit-testing jasmine


【解决方案1】:

因此,在这种情况下,实际问题是我在 URL 中有一个双字节字符,并且它在另一端进行了 URL 编码。我对文字进行了测试。相当令人沮丧。我可以通过遵循在 this thread 中使用 matchFunction 的建议来解决这个问题,这是一个很好的例子。

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多