gpt4 book ai didi

angular - 模拟 Angular Material Dialog afterClosed() 用于单元测试

转载 作者:太空狗 更新时间:2023-10-29 18:14:35 26 4
gpt4 key购买 nike

我正在使用以下函数打开我的 mat 对话框:

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(在每个测试平台创建之前)

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();
}));

component.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();
});

最佳答案

我在@Adithya Sreyaj 的第一篇文章中解决了这个问题,但添加了下一个更改:

spyOn(component.dialog, 'open')
.and
.returnValue({
afterClosed: () => of(true)
} as MatDialogRef<typeof component>);

关于angular - 模拟 Angular Material Dialog afterClosed() 用于单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56030253/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com