简体   繁体   中英

How can I mock MatDialog in order to have openDialog[index].id defined?

This is the code in my component, but since openDialogs is readable only, I'm struggling to define an array with one MatDialogRef element

ngOnInit() {
    this._dialogInstance = this.dialog.getDialogById(this.dialog.openDialogs[0].id);
    this._dialogInstance.addPanelClass(this._SCAN_GRAPHER_PANEL_CLASS);
     ...
}

in the test

matDialog = MockService(MatDialog);
const dialogInstance = MockInstance(MatDialogRef) as unknown as MatDialogRef<any, any>;
Object.assign(matDialog.openDialogs, [{ id: '0' }]);
spyOn(matDialog, 'getDialogById').and.returnValue(dialogInstance);

await TestBed.configureTestingModule({ ....})
....

and I'm getting the following error (on the line where I'm using Object.assign)

Cannot convert undefined or null to object

I sorted as following

const dialogInstance = {
      addPanelClass: (panelClasses: string | string[]) => dialogInstance,
      removePanelClass: (panelClasses: string | string[]) => dialogInstance
    } as unknown as MatDialogRef<any, any>;

    (matDialog.openDialogs as any) = [{ id: '0' }];
    matDialog.getDialogById.and.returnValue(dialogInstance);

The main thing was to wrap matDialog.openDialogs as any so I was able to set the id of the dialog

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM