繁体   English   中英

如何调试“预期一个匹配请求的条件“匹配 URL”:未找到”

[英]How to debug 'Expected one matching request for criteria “Match URL”: found none'

在我的 Angular 应用程序中,我正在测试使用HttpClient的服务,就像官方文档建议的那样:

https://angular.io/guide/http#testing-http-requests

这就是我的测试用例的样子:

it('myMethod() should correctly sent the http request', () => {
  const mockResultData = { result: 123 };

  service.myMethod(); // will trigger an http request using the httpClient

  const req = httpTestingController.expectOne('/some/path?param1=a&param2=b');

  expect(req.request.method).toEqual('GET');

  req.flush(mockResultData);

  httpTestingController.verify();
});

但是,测试失败并显示以下内容:

错误:预期有一个针对条件“匹配 URL:/some/path?param1=a&param2=b”的匹配请求,但没有找到。

现在我很清楚触发的请求并不完全是 url /some/path?param1=a&param2=b ,但是错误消息没有提到找到了哪些请求

我该如何调试它并检查实际找到了哪些请求?

诀窍是在没有expectOne的情况下运行相同的测试,因此只需使用service.myMethod()触发 http 请求,然后调用httpTestingController.verify()

it('myMethod() should correctly sent the http request', () => {
  const mockResultData = { result: 123 };

  service.myMethod(); // will trigger an http request using the httpClient

  // TEMPORARILY COMMENT THESE 3 LINES

  // const req = httpTestingController.expectOne('/some/path?param1=a&param2=b');

  // expect(req.request.method).toEqual('GET');

  // req.flush(mockResultData);

  httpTestingController.verify();
});

这样, httpTestingController.verify()方法将检查是否没有待处理的请求,否则将触发错误。 因此,因为确实有一个请求待处理,所以它现在会出错:

错误:预计没有打开的请求,发现 1:GET /some/path?param2=b&param1=a

这正是我所需要的:知道实际请求是什么。

因此,在我的情况下,问题出在交换的参数中( param2=bparam1=a )。 所以我终于可以修复我的测试用例了:

it('myMethod() should correctly sent the http request', () => {
  const mockResultData = { result: 123 };

  service.myMethod(); // will trigger an http request using the httpClient

  const req = httpTestingController.expectOne('/some/path?param2=b&param1=a'); // now the params are in the right order

  expect(req.request.method).toEqual('GET');

  req.flush(mockResultData);

  httpTestingController.verify();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM