使用Async对Angular异步代码进行单元测试

226 阅读1分钟

www.digitalocean.com/community/t…

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

async可以让Angular在一个专属的test zone里执行代码,该zone可以截获promises.

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

当所有的promises都resolved之后,whenStable触发,能够进行expectation的evaluation了。

看个例子:

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


@Component({
  selector: 'app-root',
  template: `<h1<{{ title }}</h1>


    set title

  `
})
export class AppComponent {
  title: string;

  setTitle() {
    new Promise(resolve => {
      resolve('One crazy app!');
    }).then((val: string) => {
      this.title = val;
    });
  }
}

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

如何测试:

// ...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!');
    });
  }));
});