0
votes

I am trying to figure out the best way to test a component that uses Angular Material Dialog (https://material.angular.io/components/dialog/overview)

I am using the built in testing utils from Angular (Karma, jasmine)

public deleteQualification: void() {
   let dialogRef = dialog.open(DeleteQualificationComponent, {
      height: '400px',
      width: '600px',
   });

    dialogRef.afterClosed().subscribe(result => {
          if (result){
             //delete code goes here, I want to test this
            }
   });
   
}

I'm not sure how to mock up a object that returns a observable, and then wait the response in the test..

Currently I've solved it this way:

public deleteQualification: void() {
   let dialogRef = dialog.open(DeleteQualificationComponent, {
      height: '400px',
      width: '600px',
   });

    dialogRef.afterClosed().subscribe(result => {
          if (result){
             doDelete();
            }
   });

}



//I only test this
   public doDelete:void(){

   }
1

1 Answers

0
votes

You can completely mock the MatDialog like this:

TestBed.configureTestingModule({
    // ...
    providers: [
        {
            provide: MatDialog,
            useValue: jasmine.createSpyObj({
                open: jasmine.createSpyObj({
                    afterClosed: of('your result')
                })
            })
        }
    ]
})

Or this:

{
    provide: MatDialog,
    useValue: {
        open() {
            return {
                afterClosed() {
                    return of('your result');
                }
            };
        }
    }
}

afterClosed will return an sync observable that will emit the result you want. This way, you can check doDelete is called when you have the expected result.

If you want to test the actual dialog itself by opening, you'd need to import the MatDialogModule and in your test trigger the close of the dialog. To get a reference to the dialog after it's opened, you can use openDialogs on MatDialog. Comment if this is what you want to do and I'll update my answer.