1

I have the below list of companies populated in an ng-select:

<div class="input-group">
    <ng-select role="company" id="company" class="form-control" #Company
               formControlName="company">
        <ng-option *ngFor="let c of companies" [value]="c.id">
            {{c.name}}
        </ng-option>
    </ng-select>
</div>

I am using Jest & Angular testing library to perform the required unit tests. The ng-select is a searchable drop-down where users can type in keywords. I need to be able to type some text and press enter or click on the first option in the drop down in order to select the first option.

I am currently trying the below but that does not work:

userEvent.type(screen.getByRole('company'), companyName);

Is there an appropriate way to access the ng-select? My code works fine for textboxes - it only has an issue with the ng-select.

D M
  • 5,769
  • 4
  • 12
  • 27
avdeveloper
  • 449
  • 6
  • 30

1 Answers1

2

https://www.w3.org/TR/html-aria/#index-aria-combobox

Don't override default roles

You should be able to get your select field with

const selectField = screen.queryByRole('combobox');

and then get the options with

const options = screen.queryAllByRole('checkbox');

If you need to display different options in your select you can use ng-template with ng-multi-label-tmp or ng-option and pass a data-testid="example" to whatever you wrap within the ng-template and then query that specific option with const optionA = screen.queryByTestId('example');

Check the documentation of how ng-template can be used here but you might not need it.

You should generelly never overwrite roles just for the sake of testing. ARIA roles are designed to help with accessibility (e.g screenreaders etc.).

Dharman
  • 30,962
  • 25
  • 85
  • 135
jsmunsch
  • 31
  • 3