【问题标题】:What is the purpose of using testData in Angular Testing HTTP requests在 Angular 测试 HTTP 请求中使用 testData 的目的是什么
【发布时间】:2021-01-18 14:02:40
【问题描述】:

我对使用 Angular 的使用 HttpClientTestingModule 测试 http 服务的示例中的 testData 有误解。 我的问题是这个expect(data).toEqual(testData) 是假的可能性有多大。 当我们实际上没有向后端或某些 Stub 发送真正的请求时。

资源链接:https://angular.io/guide/http#expecting-and-answering-requests

it('can test HttpClient.get', () => {
  const testData: Data = {name: 'Test Data'};

  // Make an HTTP GET request
  httpClient.get<Data>(testUrl)
    .subscribe(data =>
      // When observable resolves, result should match test data
      expect(data).toEqual(testData)
    );

  // The following `expectOne()` will match the request's URL.
  // If no requests or multiple requests matched that URL
  // `expectOne()` would throw.
  const req = httpTestingController.expectOne('/data');

  // Assert that the request is a GET.
  expect(req.request.method).toEqual('GET');

  // Respond with mock data, causing Observable to resolve.
  // Subscribe callback asserts that correct data was returned.
  req.flush(testData);

  // Finally, assert that there are no outstanding requests.
  httpTestingController.verify();
});

【问题讨论】:

    标签: angular unit-testing


    【解决方案1】:

    在这种情况下expect(data).toEqual(testData) 不可能为假。本指南想告诉您的是,如何在单元测试期间使用HttpTestingModule 提供虚假响应。

    Here 是一些使用HttpTestingModule 的示例代码。

    it('shoud return { server: string; ixid: string; img: string }', () => {
      service.getImg(0).subscribe((res) => {
        expect(res.server).toEqual('images.unsplash.com');
        expect(res.ixid).toEqual(
          'MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D'
        );
        expect(res.img).toContain('blob');
      });
      const req = httpTestingController.expectOne(
        'https://images.unsplash.com/photo-1598188306155-25e400eb5078?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1934&q=80'
      );
      req.flush(new ArrayBuffer(1229));
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      • 2020-03-12
      • 2021-07-21
      • 2018-05-22
      • 2018-12-20
      • 2020-07-25
      相关资源
      最近更新 更多