Angular: How to mock MatDialogRef while testing
I solved it by changing the component constructor to:
constructor(
public dialogRef: MatDialogRef<CustomDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: Dialog | any
)
The providers in the TestBed were:
providers: [{ provide: MatDialogRef, useValue: {} }, { provide: MAT_DIALOG_DATA, useValue: data }]
If you use at least one MatDialogRef
method, you should create a mock.
For example I use the close()
method. Without it errors would be generated so I made the below class with an empty method.
export class MatDialogRefMock {
close(value = '') {
}
}
and use that instead of an empty value, with useClass
{ provide: MatDialogRef, useClass: MatDialogRefMock },
Import MatDialogModule and MatDialogRef from angular/material/dialog instead of angular/material. Import the ModalDialogModule and provide providers for MatDialogRef in your TestBed.
Import {MatdialogModule,MatDialogRef} from '@angular/material/dialog';
TestBed.configureTestingModule({
declarations: [componentName],
imports: [MatdialogModule],
providers: [{provide : MatDialogRef, useValue : {}}]
});