2017-03-10 22 views
19

Angular 2 birim testi yazıyorum. Bileşen başlatıldıktan sonra tanımam gereken bir @ViewChild alt bileşen var. Bu durumda, ng2-bootstrap kitaplığından gelen Timepicker bileşenidir, ancak özelliklerin önemi olmamalıdır. 'dan sonra alt bileşen örneği hala tanımlanmamış.Açısal 2 birim testi - @ViewChild tanımlanmamış

Sözde kod:

sözde kod konsolu günlüğü ulaşana kadar beklendiği gibi çalışır
@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) 
    })); 
}); 

. timepickerChild tanımsızdır. Bu neden oluyor?

+1

Yanıt buldunuz mu? Aynı problemim var. – user3495469

cevap

4

Çalışması gerektiğini düşünüyorum. Belki de konfigürasyonunuzda bazı modülleri almayı unutmuşsunuzdur.

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

0

Çoğu durumda sadece yavaşlama eklemek ve gitmek iyidir: İşte test için tam koddur.

beforeEach(async(() => { 
     TestBed 
      .configureTestingModule({ 
       imports: [], 
       declarations: [TimepickerComponent], 
       providers: [], 
      }) 
      .compileComponents()