2017-03-10 3 views
19

각도 2 단위 테스트를 쓰고 있습니다. 구성 요소를 초기화 한 후 인식해야하는 @ViewChild 하위 구성 요소가 있습니다. 이 경우 ng2-bootstrap 라이브러리의 구성 요소는 Timepicker이지만 세부 사항은 중요하지 않습니다. 이후 detectChanges() 하위 구성 요소 인스턴스가 아직 정의되지 않았습니다.각도 2 단위 테스트 - @ViewChild가 정의되지 않았습니다.

의사 코드 :

의사 코드는 콘솔 로그에 도달 할 때까지 예상대로 작동
@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은 정의되지 않습니다. 왜 이런 일이 일어나는 걸까요?

+1

답변을 찾았습니까? 나는 같은 문제를 가지고있다. – user3495469

답변

4

제대로 작동해야한다고 생각합니다. 어쩌면 구성에서 일부 모듈을 가져 오는 것을 잊었을 수 있습니다.

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

대부분의 경우 단지 감속에 추가하고 당신은 갈 수 있습니다 : 여기 시험에 대한 전체 코드입니다.

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