【问题标题】:Angular 2 - testing a component with @input used in ngOnInit lifecycle hookAngular 2 - 使用 ngOnInit 生命周期钩子中使用的 @input 测试组件
【发布时间】:2016-11-25 08:25:35
【问题描述】:

目前我正在尝试测试一个子组件,该子组件接受来自主机组件的输入,并在 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.
}

在 myValue 需要在创建时存在同时能够访问 ChildComponent.transformedValue 进行断言的这种情况下,应如何测试 ChildComponent。

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

componentFixture = testBed.createComponent(LoginFormComponent)

但是 ngOnInit 已经被调用到我调用的位置

fixture.componentInstance.myValue = someValue;

我还尝试创建 HostComponent 的固定装置,虽然它有效,但我无法访问已创建的 ChildComponent 实例,我需要在 ChildComponent.transformedValue 字段上执行断言。

非常感谢您的帮助!

非常感谢!

【问题讨论】:

  • 如果您更改 @Input 值,它将触发 ngOnChanges 生命周期,所以这个问题可能有用:stackoverflow.com/questions/37408801/…
  • 感谢您的回复!事实上,给出的答案与我在下面发布的关于我如何设法从测试组件访问子组件的答案完全相同。不过感谢分享! :)

标签: javascript angular testbed


【解决方案1】:

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

通过将 TestHost 组件(写入 .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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 2017-11-13
    • 2019-11-27
    • 2017-07-10
    • 2017-01-18
    • 2017-12-06
    相关资源
    最近更新 更多