【问题标题】:How can I wait for async ngOninit to complete before testing在测试之前如何等待异步 ngOninit 完成
【发布时间】:2017-05-29 21:06:11
【问题描述】:

我有一个执行异步工作的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;
  })
};

【问题讨论】:

  • 您的程序中的其他内容如何知道何时完成?您可以检查的回调中会发生什么?
  • 在回调中有一些初始化逻辑
  • 你能扩展一下吗?给minimal reproducible example
  • 我完成了我的例子

标签: angular promise


【解决方案1】:
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

                    }
                );
}));

【讨论】:

  • ngOnint 中的所有承诺都解决后,回调不会运行
  • 从您提供的信息来看,这就是我所取得的成果。请显示更多有关配置的代码或尝试正确调试。并且无需显式调用comp.ngOnInit();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-15
  • 1970-01-01
  • 2020-03-04
  • 2014-04-03
  • 1970-01-01
  • 1970-01-01
  • 2020-02-11
相关资源
最近更新 更多