我有一个组件从服务中获取数据,该服务在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