[英]How can I test component @Input in angular?
我已经做了很多次没有问题,但由于某种原因,我无法让它工作。 在我的组件中,我有一个输入@Input data: Data
,在我的模板中,我使用该输入有条件地显示或隐藏内容。 出于某种原因,在我的测试中,即使我直接使用component.data = {props: values}
设置它,组件也不会注册数据存在,但是如果我使用fit
单独运行测试,它们运行良好。
data.component.spec.ts
beforeEach(() => {
fixture = testbed.createComponent(DataComponent);
component = fixture.componentInstance;
component.data = {values: ['a', 'b', 'c']};
fixture.detectChanges();
component.ngOnInit();
fixture.detectChanges();
});
describe('when viewing', () => {
it('should load and display data', () => {
const el = fixture.debugElement.query(By.css('[data-content]'));
expect(el).toBeTruthy();
});
}
数据组件.ts
export class DataComponent implements OnInit {
@Input() data!: Data;
constructor() {};
ngOnInit() {
console.log('init');
}
}
data.component.html
<div *ngIf="data.values.length">
<p data-content *ngFor="let value of data.values">{{value}}</p>
</div>
我得到的错误: Expected null to not be null "[data-content]"
我认为这可能是因为您正在调用fixture.detectChanges
和ngOnInit
。 您调用的第一个fixture.detectChanges
会为您调用ngOnInit
。
尝试这个:
beforeEach(() => {
fixture = testbed.createComponent(DataComponent);
component = fixture.componentInstance;
component.data = {values: ['a', 'b', 'c']};
fixture.detectChanges(); // => this will call ngOnInit
// component.ngOnInit(); // remove this line, the first fixture.detectChanges()
// calls ngOnInit for you.
});
describe('when viewing', () => {
it('should load and display data', () => {
const el = fixture.debugElement.query(By.css('[data-content]'));
expect(el).toBeTruthy();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.