【问题标题】:Expected one matching request, found 2 requests. How do I test for 2 requests预期 1 个匹配请求,找到 2 个请求。如何测试 2 个请求
【发布时间】:2019-07-18 19:17:03
【问题描述】:

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

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

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

错误:预期有一个符合条件“匹配 URL:http://localhost:8080/api/demoList”的匹配请求,但找到了 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);
});

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

【问题讨论】:

    标签: angular jasmine karma-coverage


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-01-08
      • 2017-10-26
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多