2016-10-19 20 views
3

ルータの出力であるユニットテストをユニットで実行しようとしています。コンポーネントで使用されているルータとサービスをスタブして、fixture.debugElementを使用して要素を取得してテストが機能していることを確認しようとしています。しかし、これは常にNULLとして返されます。角2ユニットテストでdebugElementを見つけることができません

テスト

import { TestBed, async, ComponentFixture } from '@angular/core/testing'; 
import { Router } from '@angular/router'; 
import { By } from '@angular/platform-browser'; 
import { DebugElement } from '@angular/core'; 

import { HeroesComponent } from './heroes.component'; 
import { HeroService } from '../hero.service'; 
import { StubHeroService } from '../testing/stub-hero.service'; 
import { StubRouter } from '../testing/stub-router'; 

let comp: HeroesComponent; 
let fixture: ComponentFixture<HeroesComponent>; 
let de:  DebugElement; 
let el:  HTMLElement; 

describe('Component: Heroes',() => { 

    beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     declarations: [HeroesComponent], 
     providers: [ 
     { provide: HeroService, useClass: StubHeroService }, 
     { provide: Router,  useClass: StubRouter } 
     ] 
    }) 
     .compileComponents() 
     .then(() => { 
     fixture = TestBed.createComponent(HeroesComponent); 
     comp = fixture.componentInstance; 
     de = fixture.debugElement.query(By.css('*')); 
     console.log(de); 
     el = de.nativeElement; 
     }); 
    })); 

    it('should create an instance',() => { 
    expect(comp).toBeTruthy(); 
    }); 

    it('should update the selected hero',() => { 
    comp.onSelect({ 
     id: 0, 
     name: 'Zero' 
    }); 
    fixture.detectChanges(); 

    expect(el.querySelector('.selected').firstChild.textContent).toEqual(0); 
    }); 
}); 

スタブルータクエリー前

export class StubRouter { 
    navigateByUrl(url: string) { return url; } 
} 
+0

ヌル何ですか? 「de」? –

+0

はい 'de'がNULLです –

+0

クエリを実行する前にコンポーネントが安定していますか? fixture.isStable()を実行して結果を投稿してください。 – pe8ter

答えて

0

要素コールfixture.detectChanges

fixture = TestBed.createComponent(HeroesComponent); 
comp = fixture.componentInstance; 

//call detect changes here 
fixture.detectChanges(); 

de = fixture.debugElement.query(By.css('*')); 
console.log(de); 
el = de.nativeElement; 
関連する問題