首页 > 解决方案 > 为什么使用 `fakeAsync` 测试不会使测试代码以异步方式运行?

问题描述

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

使用Observable fakeAsync并且tick()应该允许测试异步实体。我已经创建了测试,在我看来,它与文档中提供的代码(没有组件)相对应。不幸的是它失败了。你能解释一下为什么吗?

  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它,它会按预期工作。

标签: angular

解决方案


这似乎是 的指定行为throwError,订阅是同步处理的 - 所以您的测试或fakeAsync.

例如,Angular 组件中的这个方法:

handleClick() {
  throwError("test").subscribe(console.log, console.log);
  console.log("test2");
}

这导致:

test  
test2

推荐阅读