[英]Is it possible to get template reference variable in jasmine test?
For example in my-components-list.html I have:例如在 my-components-list.html 我有:
<my-component #first></my-component>
<my-component #second></my-component>
<my-component #third></my-component>
<input #forth/>
And I want to get it in my test like:我想在我的测试中得到它,例如:
it('test', () => {
const myComponent: HTMLElement = fixture.debugElement.query(By.someMethod('#first'));
const myInput: HTMLElement = fixture.debugElement.query(By.someMethod('#forth'));
}
You can use the template reference variables like you would use them in normal Angular code.您可以使用模板引用变量,就像在普通 Angular 代码中使用它们一样。 Define them with the @ViewChild decorator as fields in your component class:
使用 @ViewChild 装饰器将它们定义为组件类中的字段:
@ViewChild('first') first: ElementRef;
@ViewChild('second') second: ElementRef;
...
Then in your test you can access them like normal component fields: fixture.componentInstance.first
然后在您的测试中,您可以像普通组件字段一样访问它们:
fixture.componentInstance.first
I first expected a dynamic solution for this problem where i can access the elements by reference variable name but the more i think about the described solution i think it is the correct way.我首先期望这个问题的动态解决方案,我可以通过引用变量名称访问元素,但我对所描述的解决方案的思考越多,我认为这是正确的方法。 It is more typesafe and the elements are encapsulated as part of the component and not the template.
它更类型安全,元素被封装为组件的一部分,而不是模板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.