Angular 5测试:如何获得对子组件的引用 [英] Angular 5 testing: how to get a reference to the child component

查看:76
本文介绍了Angular 5测试:如何获得对子组件的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试Angular应用程序中主机组件和子组件之间的交互.我不知道如何获得对创建父组件时创建的子组件的引用.这是设置:

I'm trying to test the interaction between a host component and a child component in an Angular application. I don't know how to get a reference to the child component created when the parent gets created. Here is the setup:

child.component.spec.ts

@Component({template: `<child [data]="model"></child>`})
class HostComponent {
  public model:any;
}

describe('ChildComponent', () => {
  let hostFixture: ComponentFixture<HostComponent>;
  let childFixture: ComponentFixture<ChildComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ChildComponent, HostComponent]
    });
  }));

  beforeEach(() => {
    // this creates the child component as well, but how to get to it?
    hostFixture = TestBed.createComponent(HostComponent);

    // this creates a NEW instance of child component, not the one from the Host template
    // so it's not the instance I actually want to test
    childFixture = TestBed.createComponent(ChildComponent);
  });
});

更改hostFixture.componentInstance中的model值实际上并不会更改childFixture.componentInstancedata输入值;这就是我意识到子组件有两个实例的方式.

Changing the model value in hostFixture.componentInstance doesn't actually change the data input value of childFixture.componentInstance; that's how I realized that there are two instances of child component.

我的问题很简单,如何获得childFixture引用在HostComponent模板中找到的组件夹具,而不是引用我当前拥有的其他实例?

My question is simple, how can I get childFixture to refer to the component fixture found in the HostComponent template, instead of a different instance as I currently have it?

文档还没有'没有帮助.

推荐答案

指南,使用TestBed.createComponent创建主机组件实例,并且可以使用debugElement中选择子组件实例. ="noreferrer"> By助手:

As explained in the guide, host component instance is created with TestBed.createComponent, and child component instance can be selected from debugElement with By helper:

childDebugElement = hostFixture.debugElement.query(By.directive(ChildComponent));

或者:

childDebugElement = hostFixture.debugElement.query(By.css('child'));

这篇关于Angular 5测试:如何获得对子组件的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆