【问题标题】:Angular2 unit test select dropdown valueAngular2单元测试选择下拉值
【发布时间】:2017-11-06 09:26:44
【问题描述】:

我有一个县下拉菜单。有一个默认值。用户可以选择一个国家。在更改时,它会将用户重定向到正确的国家/地区页面。哪个正在工作。

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

【问题讨论】:

  • 这个怎么样?

标签: javascript angular unit-testing typescript jasmine


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你试试这个:

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

    【讨论】:

    • 这是一个很好的实践来解释您的解决方案需要什么。否则其他人将很难理解,尤其是那些刚接触编程世界的人
    猜你喜欢
    • 2017-02-09
    • 2019-12-24
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多