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

╄→尐↘猪︶ㄣ 提交于 2019-12-05 07:59:57

I don't know which version of Angular2 you use and how you initialize your test suite but the detectChanges method on the ComponentFixture instance is responsible to set such fields.

Here is a sample test that shows this:

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');
    });
}));

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 of

@ViewChild('componentref')

and then in your template:

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

and of course you need to init your component with componentFixture.detectChanges()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!