【问题标题】:Angular2 @Viewchild unit testAngular2 @Viewchild 单元测试
【发布时间】:2018-01-16 22:43:19
【问题描述】:

我有一个这样的组件:

export class ParentComponent implements OnInit, OnDestroy {


    @ViewChild(ChildComponent) childComponent: ChildComponent;
}

正在使用childComponent 拨打电话,我们可以这样说:

this.childComponent.method();

ParentComponent 方法内。

所以,当我尝试测试内部使用ChildComponentParentComponent 方法时,childComponent 以未定义的形式返回。

如何解决问题?

【问题讨论】:

    标签: angular unit-testing testbed


    【解决方案1】:

    在描述中为子组件声明夹具。

    let childFixture: ComponentFixture<childComponent>;
    

    现在使用

    创建组件实例
    let childComp = childFixture.componentInstance;
    

    【讨论】:

      【解决方案2】:

      在大多数情况下,当您想在测试中使用 ViewChild 时,只需将其添加到您的测试声明中,如下所示:

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

      【讨论】:

      • 对我来说仍然未定义。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-19
      • 2016-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      相关资源
      最近更新 更多