简体   繁体   中英

Angular 2 - testing a component with @input used in ngOnInit lifecycle hook

Currently I am trying to test a child component which is accepting an input from the host component, and used within the ngOnInit life cycle hook like the code below.

@Component({
   selector: 'my-child-component',
   template: '<div></div>'
})
class ChildComponent implements OnInit {
    @Input() myValue: MyObject;
    transformedValue: SomeOtherObject;

    ngOnInit():void {
        // Do some data transform requiring myValue
        transformedValue = ...;
    }
}

@Component({
    template:`<my-child-component [myValue]="someValue"></my-child-component>`
})
class HostComponent {
    someValue: MyObject = new MyObject(); // how it is initialized it is not important.
}

How should the ChildComponent be tested in this case where myValue needs the to be present upon creation while being able to have access to ChildComponent.transformedValue for assertion.

I tried creating the ChildComponent using the Angular TestBed class like this

componentFixture = testBed.createComponent(LoginFormComponent)

however the ngOnInit would have already been called up to the point where I call

fixture.componentInstance.myValue = someValue;

I also tried creating a fixture of the HostComponent, and while that works, I got stuck at getting access to the ChildComponent instance that was created, which i require to perform assertions on the ChildComponent.transformedValue field.

Help is greatly appreciated!

Thanks a lot!

Angular offers the ability to inject children components to their parent components using the @ViewChild() decorator. See https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-view-child

By updating the TestHostcomponent (that is written within the .spec.ts file) to the following

@Component({
    template:`<my-child-component [myValue]="someValue"></my-child-component>`
})
class TestHostComponent {
    @ViewChild(MyChildComponent)
    childComponent: MyChildComponent;
}

it exposes its child component instance ( and its variables ), making the assertion of the 'transformedValue' possible, as per below.

componentFixture = testBed.createComponent(TestHostComponent)
expect(componentFixture.componentInstance.childComponent.transformedValue).toEqual(...someValue);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM