我正在尝试对该材质对话框进行单元测试,以测试模板是否正在渲染正确的注入对象。正确使用该组件即可正常工作
组件-对话框
promise.then()
对话框模板
@Component({
templateUrl: './confirmation-dialog.component.html',
styleUrls: ['./confirmation-dialog.component.scss']
})
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;
}
业力错误
我尽力寻找这个问题,避免重复
答案 0 :(得分:4)
尝试一下
describe('Confirmation Dialog Component', () => {
const model: ConfirmationDialogModel = {
ActionButton: 'Delete',
SupportingText: 'Are you sure?',
};
let component: ConfirmationDialogComponent;
let fixture: ComponentFixture<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
}
]
});
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ConfirmationDialogComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', async(() => {
expect(component).toBeTruthy();
}));
});
答案 1 :(得分:0)
如果我们在组件中注入MAT_DIALOG_DATA,这里就是一个例子:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MatDialogModule } from '@angular/material/dialog'; // necesary to use components and directives of dialog module
import { MAT_DIALOG_DATA } from '@angular/material'; // necesary for inject and recip incoming data
import { ConfirmDialogComponent } from './confirm-dialog.component';
describe('ConfirmDialogComponent', () => {
let component: ConfirmDialogComponent;
let fixture: ComponentFixture<ConfirmDialogComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ConfirmDialogComponent ],
imports: [ MatDialogModule ], // add here
providers: [
{ provide: MAT_DIALOG_DATA, useValue: {} } // add here
],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ConfirmDialogComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});