我查看了angular2网站,并检查了很多SO帖子,我找不到用例说明的例子。
我想模拟来自具有@Input()标记的对象的数据。我的组件看起来像这样
...
export class DriftInfoDisplayComponent implements OnInit {
showThisDriftInfo:boolean;
headerText:string;
informationText:string;
linkText:string;
@Input() inputInfo:DriftInfo;
constructor(){}
ngOnInit() {
this.headerText = this.inputInfo.headerText;
this.informationText = this.inputInfo.informationText;
this.linkText = this.inputInfo.linkText;
this.showThisDriftInfo = this.inputInfo.visible;
}
toggleDriftInfo(){
this.showThisDriftInfo = ! this.showThisDriftInfo;
}
}
此组件的单元测试文件如下所示
describe('DriftInfoComponent', () => {
let component: DriftInfoDisplayComponent;
let fixture: ComponentFixture<DriftInfoDisplayComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ DriftInfoDisplayComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DriftInfoDisplayComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
const fixture = TestBed.createComponent(DriftInfoDisplayComponent);
const drift = fixture.debugElement.componentInstance;
expect(drift).toBeTruthy();
});
});
我想编写一个测试,在DriftInfoDisplayComponent及其属性中模拟inputInfo:DriftInfo及其对象,以便我可以测试这些数据是否在html模板中正确显示。我怎么能这样做?
感谢您提供的任何帮助!
答案 0 :(得分:9)
只需将其添加为被测组件的属性:
beforeEach(() => {
const fixture = TestBed.createComponent(DriftInfoDisplayComponent);
const drift = fixture.debugElement.componentInstance;
const driftInfo: DriftInfo = new DriftInfo();
drift.inputInfo = driftInfo;
});
it('should have input info', () => {
expect(drift.driftInfo instanceof DriftInfo).toBeTruthy();
)};
答案 1 :(得分:1)
存根一个对象,例如:
const InputInfo = {
headerText: 'headerText',
informationText: 'informationText',
linkText: 'linkText',
visible: 'visible' };
在每个前面的同步中为它分配组件属性:
beforeEach(() => {
fixture = TestBed.createComponent(DriftInfoDisplayComponent);
element = fixture.debugElement.nativeElement;
component = fixture.debugElement.componentInstance;
component.inputInfo = InputInfo; // Assign stub to component property
fixture.detectChanges(); // calls NgOnit
});
测试你的模板:
it('should have a header', () => {
const header = element.querySelector('h1').textContent;
expect(header).toBe('headerText');
});