I am trying to test a component with annotation @ViewChild. One of the functions I'm trying to test calls an element @ViewChildfor focus. However, when I try to exit a variable @ViewChild, it is always undefined. I thought it was componentFixture.detectChanges()initiating ElementRef, but that doesn't seem to be.
@ViewChild
undefined
componentFixture.detectChanges()
ElementRef
Is there any way to do this so that it is not undefined?
I do not know which version of Angular2 you are using and how you initialize your test package, but the method detectChangesin the instance ComponentFixtureis responsible for setting such fields.
detectChanges
ComponentFixture
, :
it('should set testElt', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { return tcb.createAsync(MyList).then((componentFixture: ComponentFixture) => { expect(componentFixture.componentInstance.testElt).toBeUndefined(); componentFixture.detectChanges(); expect(componentFixture.componentInstance.testElt).toBeDefined(); var testElt = componentFixture.componentInstance.testElt; expect(testElt.nativeElement.textContent).toEqual('Some test'); }); }));
. plunkr: https://plnkr.co/edit/THMBXX?p=preview.
, , , undefined, ViewChild : @ViewChild(MySubComponent)
@ViewChild(MySubComponent)
@ViewChild('componentref')
:
<my-sub-component #componentref></my-sub-component>
, , componentFixture.detectChanges()