2017-03-10 10 views
19

私は角度2ユニットテストを書いています。私はコンポーネントが初期化された後に認識する必要がある@ViewChildサブコンポーネントを持っています。この場合、ng2-bootstrapライブラリのTimepickerコンポーネントですが、詳細は重要ではありません。 I 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()