Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ''. 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>
like image 853
MonteCristo Avatar asked Jun 05 '17 14:06

MonteCristo


1 Answers

"Calling detectChanges() inside whenStable()" will populate the dropdown.

fixture.whenStable().then(() => {
  fixture.detectChanges();
  expect(selectEl.nativeElement.value).toEqual('en-ca');
});
like image 116
Praveen Avatar answered Sep 24 '22 06:09

Praveen