On console.log, ViewChild variable is undefined in

2019-04-28 10:38发布

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?

2条回答
forever°为你锁心
2楼-- · 2019-04-28 11:20

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.

查看更多
你好瞎i
3楼-- · 2019-04-28 11:35

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

查看更多
登录 后发表回答