我正在尝试对这个材料对话框进行单元测试,以测试模板是否渲染了正确的注入对象。当组件被正确使用时,它可以正常工作。
组件 - 对话框
组件 - 对话框
export class ConfirmationDialogComponent {
constructor(@Inject(MAT_DIALOG_DATA) private dialogModel: ConfirmationDialogModel) {}
}
对话框模板
<h1 mat-dialog-title *ngIf="dialogModel.Title">{{dialogModel.Title}}</h1>
<div mat-dialog-content>
{{dialogModel.SupportingText}}
</div>
<div mat-dialog-actions>
<button mat-button color="primary" [mat-dialog-close]="false">Cancel</button>
<button mat-raised-button color="primary"[mat-dialog-close]="true" cdkFocusInitial>{{dialogModel.ActionButton}}</button>
</div>
模型 - 注入内容是什么
export interface ConfirmationDialogModel {
Title?: string;
SupportingText: string;
ActionButton: string;
}
单元测试 - 我在哪里遇到了问题
describe('Confirmation Dialog Component', () => {
const model: ConfirmationDialogModel = {
ActionButton: 'Delete',
SupportingText: 'Are you sure?',
};
let component: ConfirmationDialogComponent;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
ConfirmationDialogComponent
],
imports: [
MatButtonModule,
MatDialogModule
],
providers: [
{
// I was expecting this will pass the desired value
provide: MAT_DIALOG_DATA,
useValue: model
}
]
});
component = TestBed.get(ConfirmationDialogComponent);
}));
it('should be created', async(() => {
expect(component).toBeTruthy();
}));
});
Karma错误
MatDialogRef
,则需要将其包含在providers
数组中。示例:providers: [{ provide: MatDialogRef, useValue: { close: (dialogResult: any) => { } } }]
来源 - ndraimanmockMainDialogRef
从何而来并不明显。如何获取该引用? - Elias