Unit Testing Angular Material Dialog

April 6, 2021 · 2 min readLucian Ciobanu
Tags:AngularAngularMaterialUnitTest

Material Dialogs are awesome in a way that I get quick gratification. It takes few lines of code and little effort to turn your Angular web app into a pop up popping app. And then there's unit testing them...

Here's what the component triggering the dialog looks like and also the code I was trying to test:

public addNewInfo() {
  const dialogRef = this.dialog.open(MyModalComponent, {
    width: 500px,
    data: this.values
  });
  
  dialogRef.afterClosed().subscribe(result => {
    this.newlyAdded = result;
  });
}

Few challenges I had to overcome in order to test:

  1. understand I must declare the MatDialog provider's open action
  2. inject MatDialog in the TestBed
  3. describe the typeof response when spying on the action
import { MatDialog, MatDialogModule, MatDialogRef } from '@angular/material/dialog;
import { of } from 'rxjs';
import { MyModalComponent } from '../my-modal-component/my-modal-component.component';

[...]
 
 describe('MyComponent', () => {
   [...]
   let dialog: MatDialog;
 
   beforeEach(async () => {
     await TestBed.configureTestingModule({
       providers: [
         //1.
         { provide: MatDialog, useValue { open: () => of({id: 1}) } }
       ]
       //under providers I had to describe what actions will be available on the modal - action of "open"
       //alongside providers I had declarations array
    })
    .compileComponents();
});

beforeEach(() => {
  [...]
   
   //2.
   dialog = TesBed.inject(MatDialog);
});

//now the actual test
it('should open dialog on trigger', () => {
  //3.
  spyOn(dialog, 'open').and.returnValue({afterClosed: () => of({id: 1})} as MatDialogRef<typeof MyModalComponent>);
  //this is actually where I was stuck the most as it seems that with Material 11 you need to specify the type of response it's getting
  component.addNewInfo();
  expect(dialog.open).toHaveBeenCalled();
}

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery