Ralf Schneider
Ralf Schneider

Reputation: 693

How to select an option with Angular Material 2 and Protractor?

I'm writing some e2e tests with protractor. My application is an Angular Material 2 application. In my test I want to select an option of a md-select by value. When I inspect the open md-select I see the md-option items. The values of the options are in an attribute ng-reflect-value.

Let's say I have an option with the value "optionA". How can I select a certain option by this value?

I tried this:

element(by.name('myselect')).click();
$$('.mat-option').then((options) => {
  ...
});

and inside then I see the correct number of options, but how can I select the option which has the value "opetionA" ?

Upvotes: 1

Views: 7081

Answers (3)

KVarmark
KVarmark

Reputation: 236

This example is a bit crude, but it shows how to do what you want:

html:

<mat-form-field id="your-id">
    <mat-select>
        <mat-option [value]="1">1</mat-option>
        <mat-option [value]="2">2</mat-option>
    </mat-select>
</mat-form-field>

ts:

function selectOptionByOptionValue(selectFormFieldElementId, valueToFind) {

  const formField = element(by.id(selectFormFieldElementId));
  formField.click().then(() => {

    formField.element(by.tagName('mat-select'))
      .getAttribute('aria-owns').then((optionIdsString: string) => {
        const optionIds = optionIdsString.split(' ');    

        for (let optionId of optionIds) {
          const option = element(by.id(optionId));
          option.getText().then((text) => {
            if (text === valueToFind) {
              option.click();
            }
          });
        }
      });
  });
}

selectOptionByOptionValue('your-id', '1');

Upvotes: 7

jvhang
jvhang

Reputation: 777

This works for me:

    element.all(by.cssContainingText('span.mat-option-text', "option text to search for")).click();

Got answer from this question: How to locate element by span value in protractor?

Upvotes: 3

wswebcreation
wswebcreation

Reputation: 2375

What you can do is make your css-selector "dynamic" by adding the expected value in the selector. For example

// I've place the expected value in a var to make it more clear
const optionValue = 'your-option-value';

// Open select
element(by.name('myselect')).click();
// Click on the option with your selected value
$(`.mat-option[value="${optionValue}"]`).click();

I hope this helps.

Upvotes: 3

Related Questions