@ViewChild returns undefined in unit tests with material components
See original GitHub issueBug:
When I try to access to a material component using @ViewChild from the unit tests I recieve undefined. If I use @ViewChild('element') element: ElementRef;
all is fine, but if I use for instance @ViewChild('prompt') prompt: MdSlideToggle;
the ‘prompt’ value is undefined. I need to use MdSlideToggle instead of ElementRef because I need to access to the specific properties of the component.
What is the expected behavior?
The component accessed through the @ViewChild decorator should be visible in the unit tests.
What is the current behavior?
The component accessed through the @ViewChild decorator is undefined in the unit tests.
What are the steps to reproduce?
Create the following:
- html:
<md-slide-toggle #prompt></md-slide-toggle>
- ts:
@ViewChild('prompt') prompt: MdSlideToggle;
Now create a simple unit test and try to access to the ‘prompt’ element. The value is undefined.
What is the use-case or motivation for changing an existing behavior?
Because the angular material components should be accessible from the unit tests like the common html components.
Which versions of Angular, Material, OS, TypeScript, browsers are affected?
- Angular: 4.3.6
- Material: 2.0.0-beta.10
- Windows 10
- TypeScript: 2.4.2
- All browsers
Issue Analytics
- State:
- Created 6 years ago
- Comments:8 (3 by maintainers)
Top GitHub Comments
Hello Guys, I need bit help in unit testing. It would be nice if someone can help me to write the unit test for slider and few other components. I can pay a small amount for it… Thank you
Just to leave a comment, in case others get here from a google search.
In unit tests if your test component has an incomplete template, or have an html syntax error, it will get past compiling the component (it will pass the truthy test) and any View/Conent child/ren variables will be undefined.