I'm trying to test a component that has an @ViewChild
annotation. One of the functions that I'm trying to test calls the @ViewChild
's element for focus. However, when I try to log out the @ViewChild
variable, it is always undefined
. I thought componentFixture.detectChanges()
would initiate the ElementRef
, but it doesn't seem to.
Is there any way to make it so it isn't undefined
?
I don't know which version of Angular2 you use and how you initialize your test suite but the
detectChanges
method on theComponentFixture
instance is responsible to set such fields.Here is a sample test that shows this:
See the corresponding plunkr: https://plnkr.co/edit/THMBXX?p=preview.
You didn't show your code but, probably u have that undefined because you did your ViewChild like:
@ViewChild(MySubComponent)
instead ofand then in your template:
and of course you need to init your component with
componentFixture.detectChanges()