Angular2 @Viewchild unit test
Asked Answered
L

2

8

I have a component like this:

export class ParentComponent implements OnInit, OnDestroy {


    @ViewChild(ChildComponent) childComponent: ChildComponent;
}

which is using the childComponent to make a call, let's say like this:

this.childComponent.method();

within ParentComponent method.

So, when I am trying to test the ParentComponent method which is internally using the ChildComponent, the childComponent is returning as undefined.

How to resolve the issue?

Linis answered 9/8, 2017 at 7:15 Comment(0)
G
0

Declare fixture for child component inside describe.

let childFixture: ComponentFixture<childComponent>;

And now create component instance using

let childComp = childFixture.componentInstance;
Grenoble answered 4/12, 2018 at 10:36 Comment(0)
N
-2

In most cases when you want to use ViewChild in your test, just add it to the your test decleration like this :

beforeEach(async(() => {
        TestBed
            .configureTestingModule({
                imports: [],
                declarations: [ChildComponent],
                providers: [],
            })
            .compileComponents() 
Necessitate answered 20/8, 2017 at 13:44 Comment(1)
Still undefined for me.Midkiff

© 2022 - 2024 — McMap. All rights reserved.