How to test MatDialog is opened using mock in angular unit test

Discussão em 'Angular' iniciado por Prem Kumar, Novembro 5, 2024.

  1. Prem Kumar

    Prem Kumar Guest

    I am currently using a component, in which on button click a pop-up will be opened to greet user. I am using angular Material Dialog for opening pop-up and the component code block which will call on click is

    public openMatDialog(): void {
    this.isDialogOpen = true;

    this.dialogReference = this.dialog.open(GreetComponent, {
    autoFocus: false,
    disableClose: false,
    });

    this.dialogReference.afterClosed().subscribe(
    () => {
    this.isDialogOpen = false;
    }
    );


    }

    I also need to check boolean property to indicate dialog opened and closed.

    In the component spec, I am providing mock for dialog to prevent actual dependency like below,

    export class MatDialogMock {
    open() {
    return {
    afterClosed: () => of(true)
    };
    }
    }


    in spec providers,

    { provide: MatDialog, useValue: matDialog },


    in beforeEach,

    const matDialog = new MatDialogMock();


    When I testing Dialog open like below,

    it('Greet User', () => {
    spyOn(matDialog, 'open');
    component.openMatDialog();
    expect(matDialog.open).toHaveBeenCalled();
    });


    it is getting failed with error,

    Error: Expected spy open to have been called.


    Kindly guide how to check dialog open using mock in spec.

    Continue reading...

Compartilhe esta Página