簡體   English   中英

在 Angular 測試 HTTP 請求中使用 testData 的目的是什么

[英]What is the purpose of using testData in Angular Testing HTTP requests

我對使用 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();
});

在這種情況下, expect(data).toEqual(testData)不可能為假。 本指南想告訴您的是,如何在單元測試期間使用HttpTestingModule提供虛假響應。

是一些使用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));
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM