我尝试写垫子对话测试规范,但我不能成功,问题是,它是由一个函数调用。怎么做?谢谢你的帮助。这里是我的代码
closeDialogCancelButton() {
if (this.editFormData.dirty) {
let dialogRef = this.dialogCancel.open(DialogCancel,
{
width: '250px',
disableClose: true,
data:
{
id: '1'
}
});
dialogRef.afterClosed().subscribe(result => {
if (result)
this.dialog.close();
});
} else
this.dialog.close();
}
我已经解决了嘲讽MatDialog
相同。即:
import { of } from 'rxjs';
export class MatDialogMock {
open() {
return {
afterClosed: () => of({ name: 'some object' })
};
}
}
然后将这个模拟在您的测试床配置。
providers: [{provide: MatDialog, useClass: MatDialogMock}]
扩大达尼洛的答案,并与角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
和MAT_DIALOG_DATA
:
providers: [
{ provide: MatDialogRef, useValue: {} },
{ provide: MAT_DIALOG_DATA, useValue: {} }
]