Angular2单元测试选择下拉值

时间:2017-06-05 14:55:54

标签: javascript angular unit-testing typescript jasmine

我有一个县下降。有一个默认值。用户可以选择国家/地区。在更改时,它会将用户重定向到正确的国家/地区页面这是有效的。

但是,我正在尝试在选择框中单元测试默认值。但我一直将空字符串/值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>

2 个答案:

答案 0 :(得分:1)

“调用detectChanges()内的whenStable()”将填充下拉列表。

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

答案 1 :(得分:0)

您尝试以下操作:

fixture.detectChanges();
const selectEl = fixture.debugElement.query(By.css('select'))
console.log(selectEl);
fixture.detectChanges();
fixture.whenStable();
expect(selectEl.nativeElement.value).toEqual('en-ca');