2017-09-23 25 views
0

選択メニューを取得しようとすると、正しい値でイベントが正しく発生します。発砲しているようだが、価値は変わらない。ユニットテスト選択メニュー変更イベント(更新された値を取得しない)

私は私のコンポーネントで、この選択メニューがあります:私は以下のコードのようにそれをテストしようとしているが、commponent.seasonIdはそのから変わることはありません

public changeSeason(seasonId: number) { 
    this.test = 'blah'; //for testing sake 
    console.log('change season ' + seasonId) 
    this.seasonId = seasonId; 
    this.notify.emit(this.seasonId); 
    } 

<select id="seasonDropDown" style="width:200px;height: 36px;" aria-label="Select a Season" (change)="changeSeason($event.target.value)"> 
     <option *ngFor="let item of seasons" [value]="item.id" [selected]="item.id === seasonId">Season {{item.id}}</option> 
    </select> 

私はこの変更イベントを持っているがデフォルト値。 changeSeasonメソッドで変更する必要があります。私は、私が期待してテストしたときに(component.test).toEqual(「何とか」)は、それが通過するので、この方法が発射されて知っている:

it('should emit new season on change event', fakeAsync(() => { 

     let select = fixture.debugElement.query(By.css('#seasonDropDown')).nativeElement; 

     select.value = 2; 
     select.selectedValue = 2; 

     fixture.detectChanges(); 

     select.dispatchEvent(new Event('change')); 
     tick(); 

     fixture.detectChanges(); 


     expect(component.seasonId).toEqual(2); 
     //expect(component.test).toEqual('blah'); this will pass so I know the 
     //changeSeason event is actually getting called 
    })); 

答えて

0

テストでselect要素をつかむ前に、あなたが実行する必要があります

fixture.detectChanges(); 

は、コンポーネントとそのイベントハンドラにhtml要素を正しくリンクさせる必要があります。 私の複製物をstackblitzに見てください。私は(distachEvent(...)と一緒に)変更された選択をシミュレートするための第二のオプションを選択しHTMLSelectElementのselectedIndexプロパティを使用

it('should emit new season on change event',() => { 
    fixture.detectChanges(); 
    let select = fixture.debugElement.query(By.css('#seasonDropDown')).nativeElement as HTMLSelectElement; 

    select.selectedIndex = 1; // {id:2} 
    select.dispatchEvent(new Event('change')); 
    fixture.detectChanges(); 

    expect(+component.seasonId).toEqual(2); 
    expect(component.test).toBe('blah'); 
}); 

注:ここでは単なるテストです。

私はこれが誰かを助けてくれることを願っています。

関連する問題