【发布时间】:2021-09-14 07:17:50
【问题描述】:
我正在尝试监视呼叫服务,以了解在 matdialog 关闭后是否已调用。
但我有这个错误..
TypeError: Cannot read property 'close' of undefined
但如果我不尝试关闭对话框,则“afterClosed()”订阅中的代码永远不会被调用
这是我的组件方法:
constructor(private service:CustomService,
public dialog: MatDialog,
private dialogRef:MatDialogRef<EditarGrupoDialogComponent, any>) {}
//[....]
modificar:void{
//Open dialog to edit object
this.dialogRef = this.dialog.open(EditarGrupoDialogComponent, {
width: '80%',
height: 'auto',
disableClose: true,
data: {
groupToEdit: group
}
});
//If close with modification, we send the mew version to service
this.dialogRef.afterClosed().subscribe(
resultados => {
//If there are results
if(resul){
//Peticion al servicio de historial para publicar modificacion
this.service.realiza(resul).subscribe(
resul => {
//RequestOk
// [...]
},
(err) => {
//error
this.error=true;
}
);
}// ESLE.No results
}
);
}
这是我的 spec.ts 文件:
describe('Test GComponent', () => {
let component: GComponent;
let fixture: ComponentFixture<GComponent>;
const dialogMock = new MatDialogMock();
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ GruposCComponent ],
imports:[
HttpClientTestingModule,
MatDialogModule,
NoopAnimationsModule
],
providers: [
{ provide: CustomService, useClass: ServiceMock },
{ provide: MatDialogRef, useClass: MatDialogRefMock},
{ provide: MatDialog, useValue: dialogMock}
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(GruposCComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('Clik at button, allow modify group in dialog, and save it afterClosed', ()=>{
//Espiamos el metodo 'modificarGrupoGrupo'
const spy1 = spyOn(component, 'modificar').and.callThrough();
//Espiamos el open Mat dialog
const spy2 = spyOn(component["dialog"], 'open');
//Espiamos metodo que emite suscripcion de cierre de dialog
const spy3= spyOn(component["dialogRef"],"afterClosed").and.returnValue(
of({
group: {
id: "1CESO",
refFrame: "B"
}
})
);
//Espiamos servicio de historial
//Intervenimos injeccion del servicio
const service = fixture.debugElement.injector.get(CustomService);
//Espiamos el servicio para forzar retorno de error
const spy4 =spyOn(service, 'realiza');
//Actualice view
fixture.detectChanges();
//Click the button to edit/open dialog
const botonEditar= fixture.debugElement.query(By.css('#but'));
botonEditar.nativeElement.click();
//Actualice view
fixture.detectChanges();
//Close dialog
component["dialogRef"].close();
//Actualice view
fixture.detectChanges();
expect(spy1).toHaveBeenCalled();
expect(spy2).toHaveBeenCalled();
expect(spy3).toHaveBeenCalled();
expect(spy4.calls.count()).toBe(1);
});
});
我的模拟:
export class ServiceMock {
realiza(accion:Accion):Observable<boolean>{
//Simulate ok
return of(true);
}
}
/** Mock of refDialog */
export class MatDialogRefMock {
close():void{}
afterClosed(): Observable<any>{
return of(true);
}
}
/** Mock del Dialog */
export class MatDialogMock {
open() {
return {afterClosed: () => of({
group: {
id: "1CESO",
refFrame: "B"
}
}) };
}
}
可能出了什么问题?我只需要在单击视图按钮时检查对话框是否打开,当关闭对话框并重新调整对象时,使用对象信息调用 te 服务。
谢谢你的帮助!!!
【问题讨论】:
-
在这行之前
//Close dialog component["dialogRef"].close();可以console.logcomponent['dialogRef']吗?如果未定义,这就是问题所在。 -
谢谢@AliF50,你说得对,问题是组件[“dialogRef”]是未定义的......我想是因为值是在我正在测试的方法中分配的......所以我怎么能间谍 afterClosed() ??
-
试着把这行` { provide: MatDialogRef, useClass: MatDialogRefMock} `改成
{ provide: MatDialogRef, useValue: {} },,那我觉得你应该不错。 -
谢谢!但它没有用。随着改变我得到错误
Error: <spyOn> : afterClosed() method does not exist -
删除
spy3我认为也删除component["dialogRef"].close();行。
标签: angular jasmine angular11 mat-dialog