扩展 Danilo 的答案,使用 Angular 7,您可以测试matDialog
类似于下面的内容。
测试方法为:
openExport() {
const dialogRef = this.matDialog.open(ExportComponent, {
data: {}
});
dialogRef.afterClosed().subscribe(result => {
if (result !== 'cancel') {
this.export(result);
}
});
}
我的mat-dialog-close
动作定义如下:
<div mat-dialog-actions>
<button mat-button [mat-dialog-close]="'cancel'">Cancel</button>
...
</div>
您可以使用以下测试:
describe('openExport', () => {
const testCases = [
{
returnValue: 'Successful output from dialog',
isSuccess: true
},
{
returnValue: 'cancel',
isSuccess: false
},
];
testCases.forEach(testCase => {
it(`should open the export matDialog and handle a ${testCase.isSuccess} output`, () => {
const returnedVal = {
afterClosed: () => of(testCase.returnValue)
};
spyOn(component, 'export');
spyOn(component['matDialog'], 'open').and.returnValue(returnedVal);
component.openExport();
if (testCase.isSuccess) {
expect(component.export).toHaveBeenCalled();
} else {
expect(component.export).not.toHaveBeenCalled();
}
expect(component['matDialog'].open).toHaveBeenCalled();
});
});
});
记住向您TestBed.configureTestingModule
提供matDialog
and MAT_DIALOG_DATA
:
providers: [
{ provide: MatDialogRef, useValue: {} },
{ provide: MAT_DIALOG_DATA, useValue: {} }
]