如何选择Angular Material 2和Protractor的选项?

时间:2017-05-29 05:01:34

标签: angular protractor material

我用量角器写了一些e2e测试。我的应用程序是Angular Material 2应用程序。在我的测试中,我想选择一个md-select值的选项。当我检查打开的md-select时,我看到了md-option项。选项的值在属性ng-reflect-value中。

我们可以选择值" optionA"。如何通过此值选择某个选项?

我试过了:

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

然后在里面我看到正确数量的选项,但是如何选择具有值" opetionA"的选项? ?

3 个答案:

答案 0 :(得分:5)

这个例子有点粗糙,但是它展示了如何做你想做的事情:

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

答案 1 :(得分:3)

您可以做的是通过在选择器中添加预期值来使您的css选择器“动态”。例如

// 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();

我希望这会有所帮助。

答案 2 :(得分:1)

这对我有用:

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

从这个问题得到答案:How to locate element by span value in protractor?

相关问题