简体   繁体   中英

Is it possible to get template reference variable in jasmine test?

For example in my-components-list.html I have:

<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. Define them with the @ViewChild decorator as fields in your component class:

@ViewChild('first') first: ElementRef;
@ViewChild('second') second: ElementRef;
...

Then in your test you can access them like normal component fields: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM