如何在测试之前等待异步ngOninit完成

时间:2017-05-29 12:46:56

标签: angular promise

我有一个ngOnInit方法可以执行异步工作。

异步工作完成后,如何执行expect语句?

it('test things once all the promises declared in ngOninit are resolved', () => {
  comp.ngOnInit();

  // I want to test that comp.property is like expected

});

我的组件方法如下所示:

OnInit() {
  this.asyncMethod();
};

asyncMethod() {
  this.methodThatReturnsPromise().then(() => {
    this.property = this.otherPropertyNowResolved;
  })
};

1 个答案:

答案 0 :(得分:4)

fixture = TestBed.createComponent(MyComponent);


it('test things once all the promises declared in ngOninit are resolved', async(() => {
        fixture.detectChanges();
        fixture.whenStable().then(
                    () => {
                         // This should run once ngOnInit is completed

                    }
                );
}));