![](/img/trans.png)
[英]How to access or add template reference variable from angular within jasmine
[英]Is it possible to get template reference variable in jasmine test?
例如在 my-components-list.html 我有:
<my-component #first></my-component>
<my-component #second></my-component>
<my-component #third></my-component>
<input #forth/>
我想在我的测试中得到它,例如:
it('test', () => {
const myComponent: HTMLElement = fixture.debugElement.query(By.someMethod('#first'));
const myInput: HTMLElement = fixture.debugElement.query(By.someMethod('#forth'));
}
您可以使用模板引用变量,就像在普通 Angular 代码中使用它们一样。 使用 @ViewChild 装饰器将它们定义为组件类中的字段:
@ViewChild('first') first: ElementRef;
@ViewChild('second') second: ElementRef;
...
然后在您的测试中,您可以像普通组件字段一样访问它们: fixture.componentInstance.first
我首先期望这个问题的动态解决方案,我可以通过引用变量名称访问元素,但我对所描述的解决方案的思考越多,我认为这是正确的方法。 它更类型安全,元素被封装为组件的一部分,而不是模板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.