预期 1 个匹配请求,找到 2 个请求。我如何测试 2 个请求

Expected one matching request, found 2 requests. How do I test for 2 requests

我正在开发一个 Angular 应用程序,我正在使用 Jasmine 测试该应用程序。

我想要的是用一种方法测试两个 similar HTTP 请求,例如 ngOnInit() .

我有一个 HTTP 请求在 ngOnInit() 方法中调用了两次,并且 现在编写我使用的测试用例抛出如下错误:

Error: Expected one matching request for criteria "Match URL: http://localhost:8080/api/demoList", found 2 requests.

例如,

// method to test

ngOnInit() {
  this.httpGetRequest();
  // some other code
  this.httpGetRequest();
}

this.httpGetRequest() {
  this.httpClient.get(http://localhost:8080/api/getSomeList);
}

//test case for ngOnInit()

it('should do something', () => {
  spyOn(component, 'ngOnInit').and.callThrough();
  component.ngOnInit();

  const req = httpTestingController.expectOne(`http://localhost:8080/api/getSomeList`);
  expect(req.request.method).toEqual('GET');
  req.flush(mockList);
});

如何测试多个类似 URL 的请求?

您可以使用 match 方法代替 expectOne。在您的情况下,它应该 return 一个包含 2 个元素的数组,每个元素对应一个类似的请求。