angular - 在 Angular 6 组件 ngOnInit 函数中测试 rxjs 间隔

标签 angular unit-testing jasmine rxjs

我有一个具有以下 ngOnInit 函数的组件,它轮询服务方法以获取状态更新:

ngOnInit() {
  interval(2000).pipe(
    switchMap(() => this.dataService.getStatus())
  ).subscribe((result) => {
    this.uploadStatus = result;
  );
}

我正在尝试使用以下代码测试更新是否实际发生:

beforeEach(() => {
  fixture = TestBed.createComponent(UploadComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});


it('should start checking for status updates', fakeAsync(() => {
  const dataService = TestBed.get(DataService);
  // Mock the getStatus function
  spyOn(dataService, 'getStatus').and.returnValue(Observable.create().pipe(map(() => 'woo')));
  // Should not be initialised yet
  expect(component.uploadStatus).toBeUndefined();
  tick(2000);
  expect(component.uploadStatus).toBe('woo');
}));

但是 component.uploadStatus 始终为空。我应该如何去测试这种类型的场景?理想情况下,我想随着时间的推移检查多个更新。

谢谢

最佳答案

我最终确定的是以下内容。我还必须存储订阅,以便我可以在测试结束时取消它,以防止“周期性计时器仍在队列中”错误:

ngOnInit() {
  // Store the subscription so we can unsubscribe when testing
  this.pollingSubscription = interval(2000).pipe(
    switchMap(() => this.dataService.getStatus())
  ).subscribe((result) => {
    this.uploadStatus = result;
  });
}

然后进行如下测试:

it(`init`, fakeAsync(inject([DataService],
  (dataService: DataService) => {
    const testReturns = [
      of('woo'),
      of('yay')
    ];
    let currentReturn = -1;
    spyOn(dataService, 'getStatus').and.callFake(() => {
      currentReturn++;
      return testReturns[currentReturn];
    });

    expect(component.uploadStatus).toBeUndefined();
    fixture.detectChanges();
    // expect(component.uploadStatus).toBe('Login');
    // spyOn(dataService, 'getStatus').and.returnValue(of('woo'));
    component.ngOnInit();
    tick(2000);
    expect(component.uploadStatus).toBe('woo');
    tick(2000);
    expect(component.uploadStatus).toBe('yay');

    // Unsubscribe to prevent the "periodic timers still in queue" errors
    component.pollingSubscription.unsubscribe();
})));

关于angular - 在 Angular 6 组件 ngOnInit 函数中测试 rxjs 间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52629026/

相关文章:

mysql - 如何防止移动应用程序多次登录

javascript - Angular 4 中的 HTTP post 请求单元测试

unit-testing - Jasmine karma 。经过特定次数的测试后测试失败(页面重新加载错误)

ruby - 我可以在开始的项目中以 TDD 或 BDD 为目标吗?

unit-testing - 如何在Grails中为一个AresTo关系创建有效的参数用于单元测试?

angularjs - Angular UI 网格 onRegisterApi 函数的 Jasmine 测试用例

jasmine - 仅开 Jest - addEventListener ~ 单击断言

javascript - 在 Angular 组件之间重用参数

angular - promise all 将结果转换为对象

angular - Angular 中的 @Directive 与 @Component