www.digitalocean.com/community/t…

The async utility tells Angular to run the code in a dedicated test zone that intercepts promises.

Async allows Angular to execute code in a dedicated test zone that intercepts Promises.

whenStable: allows us to wait until all promises have been resolved to run our expectations.

When all promises are resolved, whenStable can be triggered and the expectation evaluation can be carried out.

Here’s an example:

import { Component } from '@angular/core';


@Component({
  selector: 'app-root'.template: `
      

set title `

}) export class AppComponent { title: string; setTitle() { new Promise(resolve= > { resolve('One crazy app! '); }).then((val: string) = > { this.title = val; }); }}Copy the code

When the button is clicked, the title property is set using a promise.

How to test:

/ /... our imports here

describe('AppComponent'.() = > {
  let fixture: ComponentFixture<AppComponent>;
  let debugElement: DebugElement;

  beforeEach(async(() = > {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      providers: [IncrementDecrementService]
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    debugElement = fixture.debugElement;
  }));

  it('should display title'.async(() = > {
    debugElement
      .query(By.css('.set-title'))
      .triggerEventHandler('click'.null);

    fixture.whenStable().then(() = > {
      fixture.detectChanges();
      const value = debugElement.query(By.css('h1')).nativeElement.innerText;
      expect(value).toEqual('One crazy app! ');
    });
  }));
});
Copy the code