Angular Material Dialog Close Unit Test

April 7, 2021 · 1 min readLucian Ciobanu
Tags:AngularUnitTest

Another 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!

Picture of author

Web Development & Software Delivery