Estoy escribiendo una prueba de unidad Angular 2. Tengo un subcomponente @ViewChild que debo reconocer después de que se inicialice el componente. En este caso, es un componente Timepicker de la biblioteca ng2-bootstrap, aunque los detalles no deberían importar. Después detectChanges() la instancia del subcomponente aún no está definida.
Pseudocódigo:
@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) })); }); El pseudocódigo funciona como se esperaba hasta que llega al registro de la consola. El timepickerChild no está definido. ¿Por qué está pasando esto?
Creo que debería funcionar. Quizás olvidaste importar algún módulo en tu configuración. Aquí está el código completo para la prueba:
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(); })); });Asegúrese de que su componente secundario no tenga un *ngIf que se evalúe como falso. Si es así, dará como resultado que el componente secundario no esté definido.
En la mayoría de los casos, simplemente agréguelo a la declaración y estará listo para comenzar.
beforeEach(async(() => { TestBed .configureTestingModule({ imports: [], declarations: [TimepickerComponent], providers: [], }) .compileComponents()