【问题标题】:How to expect a multiple method is been called with Jasmine如何期望用 Jasmine 调用多个方法
【发布时间】:2020-03-18 11:19:05
【问题描述】:

有这个代码

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()”被多次调用?

谢谢

【问题讨论】:

  • 你知道这个特定函数被调用的次数吗?如果是,那么您可以使用“期望(无论您的间谍方法是什么).toHaveBeenCalledTimes(次数)”。

标签: angular typescript unit-testing jasmine karma-jasmine


【解决方案1】:
  • 使用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 来重复一个函数, 我会使用来自 rxjs 的 timer() 来实现更好的实现

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多