angular - 角 - 茉莉花:由于间谍而无法测试方法
问题描述
我的组件中有一些具体的方法:
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
解决方案
如果要监视函数并保留原始行为,则需要使用callThrough。
从文档:
通过使用 and.callThrough 链接 spy,spy 仍将跟踪对它的所有调用,但此外它将委托给实际实现。
在你的情况下,你会想要做:
spyOn(comp, 'show').and.callThrough()
推荐阅读
- azure-webjobs - 使用 webjob sdk 创建 web job 有什么好处
- javascript - 试图从内部函数访问函数参数
- javascript - 错误:将数据插入表时读取 ECONNRESET
- couchbase - Couchbase 同步网关 - 获取文档的先前版本?
- sql - 如何在表中找到同事ID
- r - R:参数长度为零
- angularjs - 在组件构造函数或 $onInit 函数中使用 $scope.$on?
- oracle11g - Bpel Oracle Soa 套件。有没有办法通过 configPlan 中定义的属性过滤业务事件?
- python - 使用openpyxl lib保存时无法将公式保存在excel文件下
- ios - iOS 群组照片库照片(按类别)