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

佐手、 提交于 2019-12-07 02:05:29

问题


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?


回答1:


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.




回答2:


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()



来源:https://stackoverflow.com/questions/36439450/on-console-log-viewchild-variable-is-undefined-in-unit-test

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