我有一个组件可以从View
创建子项的服务中获取数据。这些孩子仅在创建View
时可用。在下面的示例中,View
在到达测试之前未创建,因此测试2失败。
成分:
@Component({
selector: 'component-to-test',
providers: [Service],
directives: [NgFor, ChildComponent],
template: `
<child [data]="childData" *ngFor="let childData of data"></child>
})
export class ComponentToTest implements OnInit {
@ViewChildren(ChildComponent) children: QueryList<ChildComponent>;
private data: any;
public ngOnInit() {
this.getData();
}
private getData() {
// async fetch data from a service
}
}
规格:
describe('ComponentToTest', () => {
beforeEach(inject([ComponentToTest], (component: ComponentToTest) => {
component.ngOnInit();
}));
it('should initialise data', inject([ComponentToTest], (component: ComponentToTest, service: Service) => {
return service.getData().toPromise().then(() => {
expect(component.data).toBeDefined();
})
}));
it('should initialise children', inject([ComponentToTest], (component: ComponentToTest, service: Service) => {
return service.getData().toPromise().then(() => {
expect(component.children).toBeDefined();
})
}));
});
测试1通过,测试2失败。如何测试View
或Content
初始化后创建的内容?
答案 0 :(得分:2)
注入组件只会创建组件类的实例,但不会调用生命周期回调并且不会创建任何视图。
您需要使用4
代替:
TestComponentBuilder
为了确保测试在所有异步执行完成之前都没有结束,也可以像Thierry已经提到的那样使用describe('ComponentToTest', () => {
let component: ComponentToTest;
beforeEach(async(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
tcb.createAsync(ComponentToTest).then((fixture: ComponentFixture<ComponentToTest>) => {
fixture.detectChanges();
component = fixture.componentInstance;
// component.ngOnInit(); // called by `fixture.detectChanges()`
});
})));
it('should initialise children', () => {
expect(component.children).toBeDefined();
});
});
。
答案 1 :(得分:0)
我会利用async
函数:
it('should initialise children', async(inject([ComponentToTest], (component: ComponentToTest, service: Service) => {
return service.getData().toPromise().then(() => {
expect(component.children).toBeDefined();
});
})));
来自文档:
包装异步测试区中的测试功能。当完成此区域内的所有异步调用时,测试将自动完成。可用于包装注入调用