3

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.

Prem Kumar
  • 39
  • 1
  • 6

2 Answers2

0

The problem is const matDialog = new MatDialogMock();. You shouldn't get a handle on a new one, you should get a handle on the one you provided in the TestBed.

const matDialog = fixture.debugElement.injector.get(MatDialog); // get actual instance provided then your test should be good.

Check out component with a dependency in the documentation: https://angular.io/guide/testing-components-scenarios#component-with-a-dependency

AliF50
  • 16,947
  • 1
  • 21
  • 37
  • I referred the link you provided, in which it is used for service stub. But here I am checking for MatDialog open and I am using mock class for dialog to prevent actual dialog dependency. I tried with the code you mentioned but still getting same error. Thank you !! – Prem Kumar Nov 20 '20 at 06:43
0

I had a different issue with the implementation from the question. spyOn wrapped the open function which then returned undefined instead of the object with afterClosed. That obviously caused the test to crash when trying to call this.dialogReference.afterClosed() because dialogReference was undefined.

I ended up defining the MatDialogMock class like this:

class MatDialogMock {
  open = jasmine.createSpy().and.returnValue({
    afterClosed: () => of(),
  });
}

Then it started working.

Not sure this would solve the exact issue from the question, but it may definitely help anyone like me who is trying to use the implementation from the question in their own tests.

zbr
  • 6,860
  • 4
  • 31
  • 43