tallkid24
tallkid24

Reputation: 1809

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

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?

Upvotes: 8

Views: 9714

Answers (2)

PaTT
PaTT

Reputation: 126

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

Upvotes: 5

Thierry Templier
Thierry Templier

Reputation: 202286

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.

Upvotes: 3

Related Questions