Angular 5 测试 : how to get a reference to the child component

标签 angular unit-testing

我正在尝试测试 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);
  });
});

改变 model hostFixture.componentInstance 中的值实际上并没有改变 data childFixture.componentInstance 的输入值;这就是我如何意识到有两个子组件实例。

我的问题很简单,我怎样才能得到childFixture引用在 HostComponent 中找到的组件夹具模板,而不是我目前拥有的不同实例?

The docs没有帮助。

最佳答案

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

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

或者:

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

关于 Angular 5 测试 : how to get a reference to the child component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47796638/

相关文章:

angular - OidcClient.readSigninResponseState : No matching state found in storage - oidc-client-js (Angular)

Angular Testing karma - 错误 : Can't resolve all parameters for RequestOptions: (?)

ajax - Jasmine 模拟ajax与JSON

database - 如何为依赖动态数据的函数编写单元测试?

angular - 当用户单击“添加记录”按钮时如何添加记录

javascript - 从接口(interface)以编程方式创建 Typescript 用户定义的类型保护

angular - 找不到本地 "typescript"包。 "@ngtools/webpack"包 Angular 2

angular - 如何在 angular2(material2)中设置 snackbar 的持续时间

java - 如何使用PowerMock模拟除被测类之外的另一个类的私有(private)方法?

ruby-on-rails - RSpec 测试后清除 ActionMailer::Base.deliveries