Mocking Angular Material Dialog afterClosed() for unit test

I solved this problem as the first post by @Adithya Sreyaj but added the next change:

spyOn(component.dialog, 'open')
    .and
    .returnValue({
        afterClosed: () => of(true)
    } as MatDialogRef<typeof component>);

You can test Angular Material Dialog's afterClosed method this way:

  1. import { of } from 'rxjs';
  2. spy on the dialog and return an observable for the afterClosed() method
spyOn(component.dialog, 'open')
     .and
     .returnValue({afterClosed: () => of(true)});

Basically, the afterClosed() of the dialogRef is expecting an Observable. So we spy on the component's dialog open method and return an Observable for the afterClosed() method by using the of operator from rxjs.

You can then replace the of(true) from the returnValue with your own data what you are sending in the afterClosed() of the dialog in the main component.


I think you are missing the whole point of unit testing the component. From my understanding:

  1. You have a function accept() which creates subscription to the closing event of this.dialog
  2. You should write unit test to verify the logic that the subscription is getting created and the service is called.
  3. Make dialogRef global to component rather than keeping it private to accept(). This would help you test your code better. private variables can't be access during unit testing.

So:

component.ts

accept() {
 this.dialogRef = this.dialog.open(AcceptDialogComponent, {
  data: {
    hasAccepted: false
      }
    })
 this.dialogRef.afterClosed().subscribe(result => {
  console.log(result);
  if (result.hasAccepted === true) {
    this.leadService.acceptLead(this.holdingAccountId, this.lead.id)
    .pipe(
      takeUntil(this.onDestroy$)
    )
    .subscribe (acceptLeadRes => {
      console.log(acceptLeadRes);
      this.leadService.updateLeadAction('accept');
    },
    (err: HttpErrorResponse) => {
      console.log(err);
      this.router.navigate(['/error']);
    });
   }
 });
}

spec.ts

it('should create subscription to Modal closing event and call "acceptLead()" of "leadService" ', () => {
    spyOn(component.dialogRef, 'afterClosed').and.returnValue(
        of({
            hasAccepted: false
        })
    );
    spyOn(component.leadService, 'acceptLead').and.callThrough();
    component.accept();
    expect(component.dialogRef).toBeDefined();
    expect(component.dialogRef.afterClosed).toHaveBeenCalled();
    expect(component.leadService.acceptLead).toHaveBeenCalled();
});