我正在尝试测试 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/