如何调试'期望一个对标准""的匹配请求;匹配URL":没有找到'



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

https://angular.io/guide/http#testing-http请求

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

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:/一些/路径?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=

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

因此,在我的情况下,问题在于交换的参数(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();
});

最新更新