Angular-使用多个HTTP请求测试异步功能

时间:2019-07-11 15:21:10

标签: angular unit-testing jasmine angular-test angular-testing

我具有此登录功能,我想对其进行测试。但是我收到一个错误“异步回调未在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 :(得分:0)

可能有两个原因:

  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;