【问题标题】:How to debug 'Expected one matching request for criteria "Match URL": found none'如何调试“预期一个匹配请求的条件“匹配 URL”:未找到”
【发布时间】:2019-10-29 17:44:06
【问题描述】:

在我的 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,但是 错误消息没有提到找到了哪些请求

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

【问题讨论】:

    标签: angular typescript jasmine angular-httpclient angular-test


    【解决方案1】:

    诀窍是在没有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();
    });
    

    【讨论】:

      猜你喜欢
      • 2019-01-08
      • 2023-03-22
      • 2018-12-07
      • 2018-11-18
      • 2021-02-20
      • 2019-07-18
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      相关资源
      最近更新 更多