Как смоделировать объект httpClient в сервисе angular - PullRequest
0 голосов
/ 10 марта 2020

Я хочу смоделировать вызов для 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-вызовами?

1 Ответ

0 голосов
/ 10 марта 2020

Вы уже делаете 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);
  });

});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...