【发布时间】:2021-11-18 02:05:20
【问题描述】:
我正在尝试测试 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.componentInstance 的data 输入值;这就是我意识到有两个子组件实例的原因。
我的问题很简单,我怎样才能让childFixture 引用在HostComponent 模板中找到的组件夹具,而不是像我目前拥有的不同的实例?
The docs 没有帮助。
【问题讨论】:
-
一般情况下你可以使用父组件fixture访问子视图。为什么需要子组件fixture?
-
@AmitChigadani 因为我有兴趣测试组件的属性和方法,以响应主机模板中设置的输入值的变化。一个例子是测试主机和孩子之间的双向数据绑定。
-
文档为什么没有帮助?这正是那里描述的场景。
标签: angular unit-testing