簡體   English   中英

如何在角度服務中模擬 httpClient 對象

[英]How to mock httpClient object in angular service

我想模擬對 httpClient 的調用

  constructor(private httpClient: HttpClient,...) {
    this.loadData();
    this.loadAnotherDate();
  }

  loadData() {
    this.httpClient
      .get<string[]>('url')
      .subscribe(...);
  }

  loadLayer() {
    this.httpClient
      .get<Dto>('url').subscribe(...);
  }

這就是我嘗試編寫測試以通過模擬 httpClient 創建對象的方式

describe('service', () => {
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
    });

    httpMock = TestBed.get(HttpTestingController);

  });

  it('should be created', () => {
    const laodDataRequest = httpMock.expectOne('url');
    laodDataRequest.flush([]);
    const loadAnotherDataRequest = httpMock.expectOne('url');
    loadAnotherDataRequest.flush([]);

    const note = new Note(httpMock, ...);

  });

這會導致錯誤,因為不允許使用 httpMock。 我應該如何通過模擬這兩個 http 調用來創建對象?

您已經在服務本身中進行subscribes ,這可能會讓我們失望。

import { HttpClientTestingModule,
         HttpTestingController } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';

describe('service', () => {
  let httpTestingController: HttpTestingController;
  let service: Service;

  beforeEach(() => {
   TestBed.configureTestingModule({
      providers: [Service, /* your other providers mocked */],
      imports: [HttpClientTestingModule],
    });

    httpTestingController = TestBed.get(HttpTestingController);
    service = TestBed.get(Service);
  });

  afterEach(() => {
    httpTestingController.verify();
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should make a get request for loadData', () => {
    const mockData = ['hello', 'world'];
    service.loadData(); // tough for you to assert what's in the subscribe because it doesn't this method does not return the observable
    const req = httpTestingController.expectOne('url');
    expect(req.request.method).toEqual('GET');
    req.flush(mockData);
  });

  it('should make a get request for loadLayer', () => {
    const mockData = {};
    service.loadLayer(); // tough for you to assert what's in the subscribe because it doesn't this method does not return the observable
    const req = httpTestingController.expectOne('url');
    expect(req.request.method).toEqual('GET');
    req.flush(mockData);
  });

});

暫無
暫無

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

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