Angular Material Dialog Close Unit Test
April 7, 2021 · 1 min readLucian CiobanuAnother day, another unit testing challenge. I swear this feels more difficult than implementing the functionality. Right... The modal component implemented with material dialog has the following piece of code which needs to be tested:
[...]
closeModal() {
this.dialogRef.close();
}
In order to do this, I had to implement the following in the modal's component.spec.ts file:
import { MatDialogRef, MatDialogModule, MAT_DIALOG_DATA } from '@angular/material/dialog';
[...]
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ MyModalComponent ],
imports:[ MatDialogModule ],
providers: [
{ provide: MAT_DIALOG_DATA, useValue: {} },
{ provide: MatDialogRef, useValue: { close: () => {} } }
]
})
.compileComponents();
});
[...]
it('should close dialog on trigger', () => {
spyOn(diaolgRef, 'close');
component.closeModal();
expect(dialogRef.close).toHaveBeenCalled();
});
Hope this helped!
Cheers,
Lucian!

Web Development & Software Delivery