Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
  }
like image 209
Enrique_Iglesias Avatar asked Oct 23 '25 14:10

Enrique_Iglesias


1 Answers

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}]

like image 114
Danilo Mz Avatar answered Oct 26 '25 14:10

Danilo Mz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!