简体   繁体   English

Angular2 单元测试选择下拉值

[英]Angular2 unit test select dropdown value

I have a county drop down.我有一个县下拉。 There is a default value.有一个默认值。 User can select a country.用户可以选择一个国家。 On change it will redirect user to correct country page.更改时,它会将用户重定向到正确的国家/地区页面。 Which is working.哪个有效。

However, I am trying to unit test default value in select box.但是,我正在尝试对选择框中的默认值进行单元测试。 but I keep getting empty string/value selectEl.nativeElement.value to be '' .但我不断得到空字符串/值selectEl.nativeElement.value'' Any one have any ideas why?任何人有任何想法为什么?

// 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>

"Calling detectChanges() inside whenStable()" will populate the dropdown. “在whenStable() 中调用detectChanges()”将填充下拉列表。

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

You try this:你试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM