Angular 2 unit testing - @ViewChild is undefined
I think it should work. Maybe you forgot to import some module in your configuration. Here is the complete code for test:
import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { Component, DebugElement } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ExampleComponent } from './test.component';
import { TimepickerModule, TimepickerComponent } from 'ng2-bootstrap/ng2-bootstrap';
describe('Example Test', () => {
let exampleComponent: ExampleComponent;
let fixture: ComponentFixture<ExampleComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule, TimepickerModule.forRoot()],
declarations: [
ExampleComponent
]
});
fixture = TestBed.createComponent(ExampleComponent);
});
it('should recognize a timepicker', async(() => {
fixture.detectChanges();
const timepickerChild: TimepickerComponent = fixture.componentInstance.timepickerChild;
console.log('timepickerChild', timepickerChild);
expect(timepickerChild).toBeDefined();
}));
});
Plunker Example
Make sure your child component does not have a *ngIf that is evaluating to false. If so, it will result in the child component as being undefined.