Angular click select option in component test

后端 未结 3 1662
不思量自难忘°
不思量自难忘° 2021-02-05 14:06

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\'));
sele         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-05 14:14

    You don't have to dispatch a change event. First you need to click on the trigger for your dropdown, i'm assuming it's your selectEl selectEl = fixture.debugElement.query(By.css('#dropdown')).

    selectEl.click();
    fixture.detectChanges();
    

    After detectChanges your dropdown should be opened. Only after this will you be able to get your options from fixture, because before they where not present in your fixture.

    The only way I have been able to get my options is by doing const selectOptions = fixture.debugElement.queryAll(By.css('.select-option')); where 'select-option'is the class I put on the options. I am using mat-select in my project, so this might be due to that.

    You can click the first option by doing selectOptions[0].nativeElement.click();. Afterwards you need to call fixture.detectChanges() again. Now you have selected an option!

    I was able to get the value that is now selected by doing selectEl.innerText.trim(). Not sure if this is the best way to do it, but it works. Trim is used to remove the whitespace.

提交回复
热议问题