使用 asyncScheduler 和 flush 进行 Angular Testing - 为什么它会因 flush() 而失败?

标签 angular rxjs angular-test

有这个 Angular 组件:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { asyncScheduler, Observable, of, queueScheduler, scheduled } from 'rxjs';

@Component({
  selector: 'test-component',
  templateUrl: './test-component.component.html'
})
export class TestComponentComponent implements OnInit {
  value: string;

  constructor() { }

  ngOnInit(): void {
    const data$ = this.fetchDataScheduler();

    data$
      .subscribe(value => {
        this.value = value;
      });
  }

  private fetchDataScheduler(): Observable<string> {
    return scheduled(of('foo'), asyncScheduler);
  }

}


并且测试失败:

it('async - test setTimeout', fakeAsync(() => {
    expect(component.value).toBeFalsy();

    fixture.detectChanges(); // ngOnInit

    expect(component.value).toBeFalsy();
    flush();

    expect(component.value).toBe('foo');  // <- fails here
  }));

failing test
flush()应该刷新所有宏任务,但它没有。为什么?
如果我使用 tick() ,则测试通过。

passing test

(以上截图由 Jest 和 Wallaby 插件提供。)

为什么不通过 flush()但正在通过 tick() ?

flush :

Simulates the asynchronous passage of time for the timers in the fakeAsync zone by draining the macrotask queue until it is empty. The returned value is the milliseconds of time that would have been elapsed.



repo 在这里:https://stackblitz.com/github/felikf/angular-testing-examples

最佳答案

异步调度程序 setInterval这是一个周期性的宏任务,目前是 flush() API 只刷新非周期性的宏任务,例如 setTimeout()
现在您应该使用 tick() 使其工作。
您可以阅读更多相关信息 here

关于使用 asyncScheduler 和 flush 进行 Angular Testing - 为什么它会因 flush() 而失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59649391/

相关文章:

angular - 在带 Angular 选择中加载默认选项

angular - 给出特定响应时取消订阅 Angular2 方法?

angular - 单元测试后关闭 ngx-bootstrap 模式

带有模拟结构指令的 Angular 测试组件失败

Angular - 从子组件获取数据?

javascript - 如果在没有 "banana"包装的情况下使用,ngModel 是否会创建两种方式的数据绑定(bind)

javascript - 如何以正确的方式表示两个日期之间的日期数组列表?

typescript - angular2 CLI 项目中缺少一些 RxJS 运算符?该怎么办?

javascript - RxJS.Observable 是单子(monad)吗?

angular - 如何在 Angular 2 中为单元测试创​​建新事件?