首页 > 解决方案 > 如何期望用 Jasmine 调用多个方法

问题描述

有这个代码

ngOnInit() {
    this.loadFilesList(this.massiveLoadModuleConfig.CONSTANTS.FILES_LIST_REFRESH_INTERVAL);
}

private loadFilesList(interval: number): void {
    this.massiveLoadService.loadMassiveLoadFilesList().subscribe(() => this.getFilesList());

    this.timeout = setTimeout(() => {
        this.loadFilesList(interval);
    }, interval);
}

我怎么能期望在 Jasmine 中多次调用方法“massiveLoadService.loadMassiveLoadFilesList()”?

谢谢

标签: angulartypescriptunit-testingjasminekarma-jasmine

解决方案


  • 使用fakeAsync+tick
  • 我们只想测试 loadFilesList() 是否在 amount 时间后再次调用
it ('...', fakeAsync(() => {
  const spy = spyOn(massiveLoadService, 'loadFilesList').and.callThrough();
  fixture.detectChanges(); // detect change againt

  tick(); // invoke async
  tick(yourInterval);

  fixture.detectChanges(); // detect change againt
  fixture.destroy(); // kill the interval, otherwise it will continue running = error

  expect(spy).toHaveBeenCalledTimes(2);
})

注意:我不会像这样使用嵌套函数 + setInterval 来重复一个函数,我会使用timer()from rxjs 以获得更好的实现


推荐阅读