预计有 1 个匹配请求,发现 2 个请求。如何测试 2 个请求

Sau*_*pta 5 jasmine karma-coverage angular

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

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

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

错误:预期条件“匹配 URL:http://localhost:8080/api/demoList ”有 1 个匹配请求,但发现 2 个请求。

例如,

// 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);
});
Run Code Online (Sandbox Code Playgroud)

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

Eri*_*ton 5

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