Using fakeAsync to test Async Observables

The way how we can handle Observables is really similar to other scenarios we have already covered, check the following code:

it('Async test example - RxJS Observables', fakeAsync(() => {
    let test: boolean;

    console.log('Creating observable');

    const test$ = of(test);

    test$
    .pipe(
        delay(1000)
    )
    .subscribe(() => {
        test = true;
    });

    tick(1000);

    expect(test).toBeTruthy();
}));

whenStable()

Get a promise that resolves when the fixture is stable. This can be used to resume testing after events have triggered asynchronous activity or asynchronous change detection.

it("should display advanced courses when tab clicked - async", async(() => {

  coursesService.findAllCourses.and.returnValue(of(setupCourses()));

  fixture.detectChanges();

  const tabs = el.queryAll(By.css('.mat-tab-label'));

  click(tabs[1]);

  fixture.detectChanges();

  fixture.whenStable().then(() => {
    const cardTitles = el.queryAll(By.css('.mat-tab-body-active .mat-card-title'));

    expect(cardTitles.length).toBeGreaterThan(0, 'Could not find card titles');

    expect(cardTitles[0].nativeElement.textContent).toContain('Angular Security Course');
  });
}));

Last updated