gpt4 book ai didi

javascript - Angular2单元测试选择下拉值

转载 作者:太空狗 更新时间:2023-10-29 17:59:09 28 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于javascript - Angular2单元测试选择下拉值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44371764/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com