我正在使用以下函数打开我的 mat-dialog:
accept() {
let dialogRef = this.dialog.open(AcceptDialogComponent, {
data: {
hasAccepted: false
}
})
dialogRef.afterClosed().subscribe(result => {
console.log(result);
if (result.hasAccepted === true) {
this.leadService.acceptLead(this.holdingAccountId, this.lead.id)
.pipe(
takeUntil(this.onDestroy$)
)
.subscribe(acceptLeadRes => {
console.log(acceptLeadRes);
this.leadService.updateLeadAction('accept');
},
(err: HttpErrorResponse) => {
console.log(err);
this.router.navigate(['/error']);
});
}
});
}
我正在尝试为这个函数编写一个测试,只需触发afterClosed(),以便我可以检查是否调用了我的服务方法,该方法将进行后端调用。
component.spec.ts(在Testbed创建之前)
beforeEach(async (() => {
TestBed.configureTestingModule({
declarations: [LeadCardComponent, AcceptDialogComponent],
imports: [
requiredTestModules,
JwtModule.forRoot({
config: {
tokenGetter: () => {
return '';
}
}
})
],
providers: [
ApplicationInsightsService,
JwtHelperService,
// { provide: LeadsService, useValue: leadServiceSpy }
],
}),
TestBed.overrideModule(BrowserDynamicTestingModule, {
set: {
entryComponents: [AcceptDialogComponent]
}
});
TestBed.compileComponents();
}));
组件.spec.ts(测试)
it('Return from AcceptLeadDialog with hasAccepted equals true should call acceptLead endpoint', () => {
let matDiaglogref = dialog.open(AcceptDialogComponent, {
data: {
hasAccepted: false
}
});
spyOn(matDiaglogref, 'afterClosed').and.callThrough().and.returnValue({
hasAccepted: true
});
spyOn(leadService, 'acceptLead').and.callThrough();
component.acceptLead();
fixture.detectChanges();
matDiaglogref.close();
fixture.detectChanges();
expect(leadService.acceptLead).toHaveBeenCalled();
});
测试目前失败,显示"Expected spy acceptLead to have been called." 我不太明白如何测试该函数并执行某种模拟MatDialogRef的方式,以便我可以检查我的测试是否通过条件。
非常感谢任何帮助/建议
更新:采用已接受答案中的工作测试
it('Return from AcceptLeadDialog with hasAccepted equals true should call acceptLead endpoint', () => {
spyOn(component.dialog, 'open')
.and
.returnValue({
afterClosed: () => of({
hasAccepted: true
})
});
spyOn(leadService, 'acceptLead').and.callThrough();
component.acceptLead();
expect(component.dialog).toBeDefined();
expect(leadService.acceptLead).toHaveBeenCalled();
});
MatDialog
的open
方法吗?这样做可以让你返回一个你控制的模拟MatDialogRef
,并且你可以手动触发afterClosed
可观察对象以发出新值。 - Daniel W Strimpel