Enrique_Iglesias
Enrique_Iglesias

Reputation: 121

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();
  }

Upvotes: 4

Views: 11083

Answers (2)

Luke
Luke

Reputation: 855

Expanding on Danilo's answer, and with Angular 7 you can test the matDialog similarly to the below.

With the method to test being:

openExport() {
    const dialogRef = this.matDialog.open(ExportComponent, {
        data: {}
    });

    dialogRef.afterClosed().subscribe(result => {
        if (result !== 'cancel') {
            this.export(result);
        }
    });
}

And with my mat-dialog-close action defined as such:

<div mat-dialog-actions>
    <button mat-button [mat-dialog-close]="'cancel'">Cancel</button>
    ...
</div>

You can use the below tests:

describe('openExport', () => {
  const testCases = [
    {
      returnValue: 'Successful output from dialog',
      isSuccess: true
    },
    {
      returnValue: 'cancel',
      isSuccess: false
    },
  ];

  testCases.forEach(testCase => {
    it(`should open the export matDialog and handle a ${testCase.isSuccess} output`, () => {
      const returnedVal = {
        afterClosed: () => of(testCase.returnValue)
      };
      spyOn(component, 'export');
      spyOn(component['matDialog'], 'open').and.returnValue(returnedVal);
      component.openExport();

      if (testCase.isSuccess) {
        expect(component.export).toHaveBeenCalled();
      } else {
        expect(component.export).not.toHaveBeenCalled();
      }

      expect(component['matDialog'].open).toHaveBeenCalled();
    });
  });
});

Remembering to provide your TestBed.configureTestingModule with the matDialog and MAT_DIALOG_DATA:

providers: [
  { provide: MatDialogRef, useValue: {} },
  { provide: MAT_DIALOG_DATA, useValue: {} }
]

Upvotes: 1

Danilo Mz
Danilo Mz

Reputation: 499

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

Upvotes: 3

Related Questions