Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular click select option in component test

I have tried the following to try to click an option in a select dropdown none of which work.

selectEl = fixture.debugElement.query(By.css('#dropdown'));
selectEl.nativeElement.options[3].nativeElement.dispatchEvent(new Event('click'));
selectEl.queryAll(By.css('option'))[3].nativeElement.click();
selectEl.nativeElement.options[3].nativeElement.click();

After each i run fixture.detectChanges(); to run the change detection but when I go to check the elements value it hasn't changed. expect(selectEl.nativeElement.options[selectEl.nativeElement.selectedIndex].textContent).toBe('name2');

Am I missing something simple to get this to work?

like image 407
Steve Fitzsimons Avatar asked Feb 23 '18 11:02

Steve Fitzsimons


People also ask

What is fixture detectChanges ()?

fixture. detectChanges() tells Angular to run change-detection. Finally! Every time it is called, it updates data bindings like ng-if, and re-renders the component based on the updated data. Calling this function will cause ngOnInit to run only the first time it is called.


1 Answers

The way to change the selected option of a dropdown is to set the dropdown value and then dispatch a change event.

You can use this answer as reference: Angular unit test select onChange spy on empty value

In your case, you should do something like this:

  const select: HTMLSelectElement = fixture.debugElement.query(By.css('#dropdown')).nativeElement;
  select.value = select.options[3].value;  // <-- select a new value
  select.dispatchEvent(new Event('change'));
  fixture.detectChanges();
like image 59
Ayala Avatar answered Oct 13 '22 19:10

Ayala