Ich schreibe einen Angular 2 Unit Test. Ich habe eine @ViewChild
- Unterkomponente, die ich nach der Initialisierung der Komponente erkennen muss. In diesem Fall ist es eine Timepicker
-Komponente aus der ng2-bootstrap-Bibliothek, obwohl die Besonderheiten keine Rolle spielen sollten. Nach I detectChanges()
ist die Unterkomponenteninstanz immer noch undefiniert.
Pseudocode:
@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)
}));
});
Der Pseudocode funktioniert wie erwartet, bis Sie das Konsolenprotokoll erreichen. Das timepickerChild
ist undefiniert. Warum passiert das?
Ich denke es sollte funktionieren. Möglicherweise haben Sie vergessen, ein Modul in Ihre Konfiguration zu importieren. Hier ist der vollständige Code für den 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();
}));
});
In den meisten Fällen wird es nur zur Verzögerung hinzugefügt und Sie können loslegen.
beforeEach(async(() => {
TestBed
.configureTestingModule({
imports: [],
declarations: [TimepickerComponent],
providers: [],
})
.compileComponents()
Stellen Sie sicher, dass Ihre untergeordnete Komponente keine * ngIf hat, die mit false ausgewertet wird. In diesem Fall ist die untergeordnete Komponente nicht definiert.