我试图在一个Angular 应用程序中测试主组件和子组件之间的交互.我不知道如何在创建父组件时获取对子组件的引用.以下是设置:

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输入值;这就是我如何意识到有两个子组件的实例.

我的问题很简单,我怎样才能得到childFixture来引用HostComponent模板中的组件fixture ,而不是我目前拥有的另一个实例?

The docs美元没用.

推荐答案

the guide所述,主机组件实例是用TestBed.createComponent创建的,子组件实例可以从debugElementBy helper中 Select :

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

或者:

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

Angular相关问答推荐

FormArray包含嵌套的FormGroups.如何访问嵌套的表单组控件?

Angular 17自定义指令渲染不起作用'

如何在投影项目组周围添加包装元素?

Primeng 12Angular 12自定义库:错误符号字段集声明于...在编译保存后未从Primeng/fieldset中导出

如何在HTML外部项目中使用Web组件(以17角创建)

角material 17 -如何从Style.scss中的主题中获取原色

从canActivate创建时,Angular material 对话框不接收MAT_DIALOG_DATA

元素上的Angular 管道链接不起作用

如何在运行Angular应用程序的容器中访问Docker容器?

Angular APP_INITIALIZER 中的 MSAL 身份验证

正确理解 angular14 中的注入 - 必须从注入上下文中调用注入()

获取从(keypress)angular2按下的键

由router-outlet 创建时如何将css类应用于组件元素?

ConnectionBackend 没有提供程序

检测指令中输入值何时更改

Angular 6在输入键上添加输入

Angular 2中不同页面的多种布局

如何每隔一段时间发出 HTTP 请求?

formGroup 需要一个 FormGroup 实例

我应该在 Angular 4+ 应用程序中 for each 组件创建一个模块吗?