Angular 2+中如何测试MatDialog关闭时调用resend方法?
如何测试MatDialog关闭时resend方法是否被调用?
我需要测试当MatDialog关闭时,resend方法是否被调用,该如何实现?
业务代码
private openResendDialog(id: number) { const matAlertDialog = this.dialog.open(MatAlertDialogComponent, { disableClose: true, data: { message: this.translateService.instant('table.resend_message'), type: 'confirm', }, }); matAlertDialog.afterClosed() .pipe(takeUntil(this.destroyed$)) .subscribe(result => { if (result) { this.resend(id); } }); }
已编写的测试代码(SPEC.TS)
it('#openResendDialog', () => { const openResendDialogSpy = spyOn(component.dialog,'open').and.returnValue({ afterClosed:() => of([1]), } as MatDialogRef<typeof component>); const fakeParam = { disableClose: true, data: { message: translateServiceMock.instant('table.resend_message'), type: 'confirm', }, }; component['openResendDialog'](1); fixture.detectChanges(); expect(openResendDialogSpy).toHaveBeenCalledWith(MatAlertDialogComponent,fakeParam); })
解决方案
要验证对话框关闭时resend方法是否被调用,你需要完成以下步骤:
- 创建resend方法的监听Spy:通过
spyOn监听组件的resend方法,追踪它的调用状态和传入参数。 - 模拟对话框关闭的返回值:业务代码中仅当
result为真值时触发resend,因此要让afterClosed()返回of(true)来模拟用户确认的场景;也可以用of(false)验证取消场景下resend不被调用。 - 添加断言验证调用情况:调用
openResendDialog后,断言resend的调用状态和参数是否符合预期。
修改后的测试代码示例
it('#openResendDialog should call resend when dialog closes with confirm', () => { // 1. 监听resend方法 const resendSpy = spyOn(component, 'resend'); // 2. 模拟对话框关闭返回true const openSpy = spyOn(component.dialog, 'open').and.returnValue({ afterClosed: () => of(true), } as MatDialogRef<MatAlertDialogComponent>); const testId = 1; component['openResendDialog'](testId); fixture.detectChanges(); // 验证对话框打开参数正确 const expectedConfig = { disableClose: true, data: { message: translateServiceMock.instant('table.resend_message'), type: 'confirm', }, }; expect(openSpy).toHaveBeenCalledWith(MatAlertDialogComponent, expectedConfig); // 验证resend被调用且参数正确 expect(resendSpy).toHaveBeenCalledOnceWith(testId); }); // 额外验证:取消对话框时resend不触发 it('#openResendDialog should NOT call resend when dialog closes with cancel', () => { const resendSpy = spyOn(component, 'resend'); spyOn(component.dialog, 'open').and.returnValue({ afterClosed: () => of(false), } as MatDialogRef<MatAlertDialogComponent>); component['openResendDialog'](1); fixture.detectChanges(); expect(resendSpy).not.toHaveBeenCalled(); });
关键注意点
- 若
resend是私有方法,需用spyOn(component, 'resend' as any)来创建监听(根据TypeScript配置调整)。 - 监听Spy必须在调用
openResendDialog之前创建,否则无法捕获调用行为。
内容的提问来源于stack exchange,提问作者Rotenberg
相关产品推荐
相关产品推荐

