Search code examples
angularjasmineangular-test

How to wait for an xhr request in an angular test


I have a component with a button. When the button is clicked, an HTTP request is made:

this.tokensService.create(this.userInCreation).subscribe(nextCb, errorCb);

How do I wait for this request to be completed? Using the async utility and fixture.whenStable does not help me.

For example:

it('', async( async () => {
    fixture.detectChanges();

    appPage.loginButtonEl.click(); // XHR request is initiated here
    fixture.detectChanges();

    await fixture.whenStable();

    // HTTP request is still pending here
}))

Solution

  • Wrap your test with fakeAsync and add tick() inside your test.

    it('', fakeAsync( async () => {
      fixture.detectChanges();
    
      appPage.loginButtonEl.click(); // XHR request is initiated here
    
      tick();
    
      fixture.detectChanges();
    
      await fixture.whenStable();
    
      // HTTP request is still pending here
    }))
    

    Reference:
    https://angular.io/api/core/testing/tick
    https://angular.io/api/core/testing/fakeAsync