首页 > 解决方案 > 角 - 茉莉花:由于间谍而无法测试方法

问题描述

我的组件中有一些具体的方法:

public show(summary: GridSummary) {
    this.resetModal(summary);
    this.summary.direction = this.summary.direction || 'Response';
    this.title = this.getTitle(summary);
    this.parentId = this.summary.id;
    this.parentType = 'Dcc' + this.summary.direction;
    this.openModal(this.dialog);
    this.auditService.getAudits(this.summary.pipelineId).subscribe(
      (summaries) => { this.populateTabs(summaries); },
      (error) => this.showSubmitError(error));
  }

 public hasSummaries(): boolean {
    return this.auditSummaries && this.auditSummaries.length > 0;
  }

 private populateTabs(summaries: AuditSummary[]) {
    this.auditSummaries = summaries;
    if (this.isFailed()) {
      if (this.isDtcFlow() || this.isDataExport()) {
        this.getErrorDetails();
      } else {
        this.getComments(false);
      }
    } else {
      if (this.isRequest()) {
        this.getComments(false);
      }
      this.dataReady = true;
    }
  }

auditSummaries 是从 show 方法中设置的。

所以在我的规范文件中,我在我的 show 方法上放置了一个间谍。

环境:

showSpy = spyOn(comp, 'show');

在我的每一个之前。然后在我的“它”测试中:

it('Show shows the model', async(() => {
        fixture.detectChanges();
        expect(showSpy).toHaveBeenCalled();
      }));

这个测试很好。我遇到的问题是尝试测试 hasSummaries 是否设置为:

it('hasSummaries return true after show', async(() => {
        fixture.detectChanges();
        fixture.whenStable().then(() => {
          expect(comp.hasSummaries()).toBe(true);
        });
      }));

因为我在主要方法上使用了间谍,所以审计服务并没有真正被调用。所以我不能以上述方式测试hasSummaries。我该如何测试这个。

我正在使用 Angular 9、Jasmine 3.5、Karma 4.4

标签: angularjasmine

解决方案


如果要监视函数并保留原始行为,则需要使用callThrough

从文档:

通过使用 and.callThrough 链接 spy,spy 仍将跟踪对它的所有调用,但此外它将委托给实际实现。

在你的情况下,你会想要做:

spyOn(comp, 'show').and.callThrough()

推荐阅读