繁体   English   中英

Angular 2 - 使用ngOnInit生命周期钩子中使用的@input测试组件

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

目前我正在尝试测试一个子组件,它接受来自主机组件的输入,并在ngOnInit生命周期钩子中使用,如下面的代码。

@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.
}

在这种情况下,应该如何测试ChildComponent,其中myValue需要在创建时出现,同时能够访问ChildComponent.transformedValue以进行断言。

我尝试使用像这样的Angular TestBed类创建ChildComponent

componentFixture = testBed.createComponent(LoginFormComponent)

但是ngOnInit已经调到我打电话的地步

fixture.componentInstance.myValue = someValue;

我也尝试创建HostComponent的一个fixture,虽然这有效,但我仍然无法访问创建的ChildComponent实例,我需要在ChildComponent.transformedValue字段上执行断言。

非常感谢帮助!

非常感谢!

Angular提供了使用@ViewChild()装饰器将子组件注入其父组件的功能。 请参阅https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-view-child

通过将TestHostcomponent(在.spec.ts文件中写入)更新为以下内容

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

它暴露了它的子组件实例(及其变量),使得'transformedValue'的断言成为可能,如下所示。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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