Как выполнить модульное тестирование метода Asyn c, который возвращает Promise - PullRequest
0 голосов
/ 28 февраля 2020

Я пытаюсь проверить службу с помощью метода, который возвращает обещание в моем приложении Angular.

Но я продолжаю получать сообщение об ошибке Asyn c функция не завершилась в течение 5000 мс

Мой сервис выглядит так

  public async startApp(data) {
    if (data === { }) this.logout()
    const url = environment.API_HOST + environment.ENDPOINT + '/start-app'
    return this.sendRequest<responseType>(url, data).toPromise()
  }

  private sendRequest<T>(url: string, data: any): Observable<T> {
    return this.http.post<T>(
      url, data, { headers: this.headers(), observe: 'response', responseType: 'json' }
    ).pipe(
      map((resp: any) => {
        return resp.body
      }))
  }

А мой файл spe c выглядит так:

describe('MyService', () => {
      let service: MyService

      TestBed.configureTestingModule({ providers: [ MyService ] })

      service = TestBed.get(MyService)
    })

    it('should start app', async (done: DoneFn) => {
       const res = await service.startApp({ data: 'someData' })
       done()
    })

Что я делаю не так?

Если возможно, я бы не стал шпионить за sendRequest, так как это частный метод, и я не могу проверить это иначе

1 Ответ

1 голос
/ 28 февраля 2020

Видя, что ваше приложение выполняет http, вам нужно внедрить его в свою конфигурацию.

import { HttpClientTestingModule,
         HttpTestingController } from '@angular/common/http/testing';
......
describe('MyService', () => {
  let httpTestingController: HttpTestingController;
  let service: MyService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [MyService],
      imports: [HttpClientTestingModule],
    });
    // get a handle on the HTTPController
    httpTestingController = TestBed.get(HttpTestingController);
    service = TestBed.get(CoursesService);
  });

  afterEach(() => {
    // verify no pending requests after each test
    httpTestingController.verify();
  });

  it('should start app and send a post request', async (done: DoneFn) => {
       service.startApp({ data: 'someData' }).then(response => {
         expect(response.body).toBe('helloWorld');
         // put the rest of your assertions here.
         done();
       });
       const mockResponse = { body: 'helloWorld' }; // mock the response to what you would like
       const req = httpTestingController.expectOne(... put here whatever the url, data is/ will resolve to);
       expect(req.request.method).toEqual('POST');
       // for the next HTTP request for that URL, give this as the response
       req.flush(mockResponse);
  });
});

startApp вызывает функцию, которая делает вызов API видимым образом, но вы преобразуете это в обещание , но я почти уверен, что то, что я вам предоставил, должно быть хорошо для go.

Хорошая ссылка для вас: https://medium.com/better-programming/testing-http-requests-in-angular-with-httpclienttestingmodule-3880ceac74cf

...