Angular - тестирование асинхронной функции с несколькими запросами http - PullRequest
0 голосов
/ 11 июля 2019

У меня есть эта функция входа в систему, и я хотел бы проверить ее. Но я получаю сообщение об ошибке «Асинхронный обратный вызов не был вызван в течение 5000 мс»

public async Login(email: string, password: string): Promise<any> {
    const body = { email, password };
    await this.getCSRFToken().toPromise();
    return this.http
      .post<any>(this.baseUrl + 'login', body)
      .pipe(
        tap(data => {
          this.user = data;
          return this.user;
        })
      )
      .toPromise();
  }

Мой тест:

it('should login', (done) => {
    const service: AuthenticationService = TestBed.get(AuthenticationService);
    const http = TestBed.get(HttpTestingController);
    let userResponse;

    service.Login('email', 'password').then((response) => {
      userResponse = response;
    });

    http.expectOne((req) => {
      return req.method === 'POST'
        && req.url === '/frontend/login';
    }).flush({user_type: 'Test'});
    expect(userResponse).toEqual({user_type: 'Test'});

  });

Есть идеи ??

1 Ответ

0 голосов
/ 11 июля 2019

Возможно, это может быть по двум причинам:

  1. Вы забыли добавить функцию done() в конце.

    it('should login', (done) => {
      const service: AuthenticationService = TestBed.get(AuthenticationService);
      const http = TestBed.get(HttpTestingController);
      let userResponse;
    
      service.Login('email', 'password').then((response) => {
        userResponse = response;
      });
    
      http.expectOne((req) => {
        return req.method === 'POST'
        && req.url === '/frontend/login';
      }).flush({user_type: 'Test'});
      expect(userResponse).toEqual({user_type: 'Test'});
      done(); // missed done function 
    });
    
  2. Вам необходимо увеличить время ожидания по умолчанию jasmine.DEFAULT_TIMEOUT_INTERVAL. `

    Это может быть установлено глобально, вне любого данного описания.

    jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
    
...