2017-06-05 69 views
4

我有一個縣下拉。有一個默認值。用戶可以選擇一個國家。在更改它將重定向用戶到正確的國家頁面。哪個在工作。Angular2單元測試選擇下拉值

但是,我想單元測試在選擇框中的默認值。但我一直得到空字符串/值selectEl.nativeElement.value''。任何人有任何想法爲什麼?

// locale-component.ts 
import { Component, OnInit } from '@angular/core'; 
import { Router, ActivatedRoute, Params } from '@angular/router'; 
import { cultures} from '../../../config/config'; 

@Component({ 
    selector: 'app-locale', 
    templateUrl: './locale.component.html', 
    styleUrls: ['./locale.component.scss'] 
}) 
export class LocaleComponent { 

    cultures = cultures; 

    constructor() {} 

    onLocaleChange(locale) { 
    const str = window.location.href.replace(new RegExp(`/${this.cultures.default}/`), `/${locale}/`); 
    window.location.assign(str); 
    } 
} 


    // locale.component.spec.ts 

    beforeEach(() => { 
    fixture = TestBed.createComponent(LocaleComponent); 
    component = fixture.componentInstance; 
    component.cultures = { 
     default: 'en-ca', 
     supported_cultures: [ 
     { "name": "United States", "code": "en-us" }, 
     { "name": "Canada (English)", "code": "en-ca" }, 
     { "name": "Canada (Français)", "code": "fr-ca" } 
     ] 
    } 
    fixture.detectChanges(); 
    }); 

    it('should create',() => { 
    expect(component).toBeTruthy(); 
    }); 

    it('should select the correct flag/locale by default',() => { 
    fixture.detectChanges(); 
    const selectEl = fixture.debugElement.query(By.css('select')) 
    console.log(selectEl) 
    fixture.detectChanges(); 
    fixture.whenStable().then(() => { 
     expect(selectEl.nativeElement.value).toEqual('en-ca'); 
    }); 

    }); 


<!-- locale.component.html --> 

<label class="locale locale--footer"> 
    <div class="locale__custom-select locale__custom-select__button locale__custom-select__ff-hack"> 
    <select [ngModel]="cultures.default" (ngModelChange)="onLocaleChange($event)"> 
     <option *ngFor="let locale of cultures.supported_cultures" [ngValue]="locale.code">{{locale.name}}</option> 
    </select> 
    </div> 
</label> 
+1

你過得怎麼樣? –

回答

1

「調用detectChanges()內部whenStable()」將填充下拉菜單。

fixture.whenStable().then(() => { 
    fixture.detectChanges(); 
    expect(selectEl.nativeElement.value).toEqual('en-ca'); 
});