On the .log console, the ViewChild variable is undefined in unit test

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.

Is there any way to do this so that it is not undefined?

+4
source share
2 answers

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.

, :

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.

+2

, , , undefined, ViewChild : @ViewChild(MySubComponent)

@ViewChild('componentref')

:

<my-sub-component #componentref></my-sub-component>

, , componentFixture.detectChanges()

+2

All Articles