I am writing an Angular 2 unit test. I have a @ViewChild
subcomponent that I need to recognize after the component initializes. In this case it's a Timepicker
component from the ng2-bootstrap library, though the specifics shouldn't matter. After I detectChanges()
the subcomponent instance is still undefined.
Pseudo-code:
@Component({
template: `
<form>
<timepicker
#timepickerChild
[(ngModel)]="myDate">
</timepicker>
</form>
`
})
export class ExampleComponent implements OnInit {
@ViewChild('timepickerChild') timepickerChild: TimepickerComponent;
public myDate = new Date();
}
// Spec
describe('Example Test', () => {
let exampleComponent: ExampleComponent;
let fixture: ComponentFixture<ExampleComponent>;
beforeEach(() => {
TestBed.configureTestingModel({
// ... whatever needs to be configured
});
fixture = TestBed.createComponent(ExampleComponent);
});
it('should recognize a timepicker'. async(() => {
fixture.detectChanges();
const timepickerChild: Timepicker = fixture.componentInstance.timepickerChild;
console.log('timepickerChild', timepickerChild)
}));
});
The pseudo-code works as expected until you reach the console log. The timepickerChild
is undefined. Why is this happening?