Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'));
}
like image 350
Stanisalv Dontsov Avatar asked Nov 07 '22 03:11

Stanisalv Dontsov


People also ask

How do I get the template reference variable in component?

To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .

Can we use template reference variable in component?

A template reference variable is often a reference to a DOM element within a template. It can also be a reference to an Angular component or directive or a web component (Read more at Angular.io). That means you can easily access the variable anywhere in the template.

Why do we need template reference variables?

A template reference variable is a feature that allows us to gain access to a part of our template. This could be an element, component, or could be a directive.


1 Answers

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.

like image 143
Markus Hettich Avatar answered Nov 14 '22 22:11

Markus Hettich