Angular 6: How to write jasmine test spec for a mat-dialog

Enrique_Iglesias picture Enrique_Iglesias · Jul 3, 2018 · Viewed 8.6k times · Source

I trying to write a test spec for mat-dialog, but i could not be success, the problem is that it is called by a function. How to do that? Thanks for your help. Here is my code

closeDialogCancelButton() {
    if (this.editFormData.dirty) {
      let dialogRef = this.dialogCancel.open(DialogCancel,
        {
          width: '250px',
          disableClose: true,
          data:
          {
            id: '1'
          }
        });
      dialogRef.afterClosed().subscribe(result => {
        if (result)
          this.dialog.close();
      });
    } else
      this.dialog.close();
  }

Answer

Danilo Mz picture Danilo Mz · Oct 9, 2018

I've solved the same by mocking MatDialog. i.e:

import { of } from 'rxjs';

export class MatDialogMock {
    open() {
        return {
            afterClosed: () => of({ name: 'some object' })
        };
    }
}

Then provide this mock in your TestBed config.

providers: [{provide: MatDialog, useClass: MatDialogMock}]