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

你。 提交于 2020-07-09 12:57:49

问题


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" ?


回答1:


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



回答2:


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.




回答3:


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?



来源:https://stackoverflow.com/questions/44234895/how-to-select-an-option-with-angular-material-2-and-protractor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!