I have a dropdown menu for selecting countries. It defaults to a pre-selected value, and when the user changes it, they are redirected to the corresponding country page.
However, I am facing an issue while trying to unit test the default value in the select box. The selectEl.nativeElement.value
keeps returning an empty string ''
. Does anyone have any insights on why this might be happening?
// locale-component.ts
import { Component } from '@angular/core';
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>