Angular2 @Viewchild unit test

I have a component like this:

export class ParentComponent implements OnInit, OnDestroy {


    @ViewChild(ChildComponent) childComponent: ChildComponent;
}

      

which uses childComponent

to make the call, let's say:

this.childComponent.method();

      

inside the method ParentComponent

.

So, when I try to test a method ParentComponent

that internally uses childComponent

, childComponent is returned as undefined.

How to solve a problem?

+6


source to share


2 answers


Declare an attribute for the child component inside.

let childFixture: ComponentFixture<childComponent>;

      



And now instantiate the component using

let childComp = childFixture.componentInstance;

      

0


source


Most of the time, when you want to use the ViewChild in your test, just add it to your test declaration like this:



beforeEach(async(() => {
        TestBed
            .configureTestingModule({
                imports: [],
                declarations: [ChildComponent],
                providers: [],
            })
            .compileComponents() 

      

-2


source







All Articles