为什么使用`fakeAsync`测试不能使测试代码以异步方式运行?

时间:2020-10-26 08:58:22

标签: angular

根据有角度的文档https://angular.io/guide/testing-components-scenarios#async-test-with-fakeasync

使用Observable fakeAsynctick()应该可以测试异步实体。 我已经创建了测试,我认为它与docs(不包含组件)中提供的代码相对应。不幸的是,它失败了。你能解释为什么吗?

  it('how to test observables. Example #5', fakeAsync(() => {
    let progress = true;
    // of(['somevalemiitter']) //without asapScheduler, it will fail
    throwError('bleblebl') //without asapScheduler, it will fail
      .pipe(finalize(() => {
        progress = false;
        // done();
      }))
      .subscribe(console.log, err => console.log(err));
    expect(progress).toBeTruthy();
    console.log('before tick');
    tick();
    console.log('after tick');
    expect(progress).toBeFalsy();
  }));

输出;

'bleblebl'
'before tick'
'after tick'

我希望它在哪里

'before tick'
'bleblebl'
'after tick'

仅因为使用fakeAsync。如果我使用asapScheduler,它将按预期工作。

1 个答案:

答案 0 :(得分:2)

这似乎是210951094的指定行为,订阅是同步处理的-因此您的测试或throwError没什么问题。

例如Angular组件中的此方法:

fakeAsync

结果是:

handleClick() {
  throwError("test").subscribe(console.log, console.log);
  console.log("test2");
}
相关问题