I have a component that gets data from a service which creates children on the View
. Those children are only available when the View
is created. In my example below the View
is not created before it reaches its tests, thus test 2 fails.
component:
@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
}
}
spec:
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();
})
}));
});
Test 1 passes, test 2 fails. How do you test something that is created after the View
or Content
is initialised?