Angular how to test MatDialog functions - open and close

Viewed 106

I'm trying to test MatDialog open and close functions. Anything I'm trying even the open function can't be tested or the close function. How can I mock and actually test it? If I'm doing like in my code I will get this error for spyOn on the 'close' function: "Argument of type '"close"' is not assignable to parameter of type 'keyof MatDialog'" TS:

//... imports etc.
dialogRef:MatDialogRef<DialogComponent>

constructor(public dialogService:MatDialog){}

public test(){
this.openProgressDialog();
//http request
this.closeProgressDialog();
}

public openProgressDialog(){
this.dialogRef=this.dialogService.open(DialogComponent,{
  disableClose:true,
  height:'150px',
  width:'400px'
});
}

public closeProgressDialog(){
  this.dialogRef.close();
}

spec.ts:

//... imports
describe("TestComponent",()=>{
   beforeEach(async () => {
   await TestBed.configureTestingModule({
   imports:[appModule,MatDialogModule],
   providers:[DialogComponent],
}).compileComponents();
 
  fixture=TestBed.createComponent(TestComponent);
  component=fixture.componentInstance;
  fixture.detectChanges();
})

test("should test", ()=>{
  spyOn(component.dialogService,'open').and.call.Through(); // the problem is at this two lines
  spyOn(component.dialogService,'close').and.call.Through(); 
  component.test();
  //expect ... (just for example)
})
1 Answers

I believe that you have an extra dot

test("should test", ()=>{
  spyOn(component.dialogService,'open').and.callThrough(); 
  spyOn(component.dialogService,'close').and.callThrough();
 
  component.test();
  
  expect(component.dialogService.open).toHaveBeenCalled();
  expect(component.dialogService.close).toHaveBeenCalled();
})
Related