如何在下拉量角器js e2e测试中选择选项

时间:2013-10-25 21:08:08

标签: javascript angularjs selenium testing protractor

我正在尝试使用量角器从角落e2e测试的下拉列表中选择一个选项。

以下是选择选项的代码段:

<select id="locregion" class="create_select ng-pristine ng-invalid ng-invalid-required" required="" ng-disabled="organization.id !== undefined" ng-options="o.id as o.name for o in organizations" ng-model="organization.parent_id">
    <option value="?" selected="selected"></option>
    <option value="0">Ranjans Mobile Testing</option>
    <option value="1">BeaverBox Testing</option>
    <option value="2">BadgerBox</option>
    <option value="3">CritterCase</option>
    <option value="4">BoxLox</option>
    <option value="5">BooBoBum</option>
</select>

我试过了:

ptor.findElement(protractor.By.css('select option:1')).click();

这会给我以下错误:

指定了无效或非法字符串 构建信息:版本:'2.35.0',修订版:'c916b9d',时间:'2013-08-12 15:42:01' 系统信息:os.name:'Mac OS X',os.arch:'x86_64',os.version:'10 .9',java.version:'1.6.0_65' 驱动程序信息:driver.version:未知

我也尝试过:

ptor.findElement(protractor.By.xpath('/html/body/div[2]/div/div[4]/div/div/div/div[3]/ng-include/div/div[2]/div/div/organization-form/form/div[2]/select/option[3]')).click();

这会给我以下错误:

  

ElementNotVisibleError:元素当前不可见,因此可能无法与之交互   命令持续时间或超时:9毫秒   构建信息:版本:'2.35.0',修订版:'c916b9d',时间:'2013-08-12 15:42:01'   系统信息:os.name:'Mac OS X',os.arch:'x86_64',os.version:'10 .9',java.version:'1.6.0_65'   会话ID:bdeb8088-d8ad-0f49-aad9-82201c45c63f   驱动程序信息:org.openqa.selenium.firefox.FirefoxDriver   Capabilities [{platform = MAC,acceptSslCerts = true,javascriptEnabled = true,browserName = firefox,rotating = false,locationContextEnabled = true,version = 24.0,cssSelectorsEnabled = true,databaseEnabled = true,handlesAlerts = true,browserConnectionEnabled = true,nativeEvents = false ,webStorageEnabled = true,applicationCacheEnabled = false,takesScreenshot = true}]

任何人都可以帮我解决这个问题,或者说明我在这里做错了什么。

33 个答案:

答案 0 :(得分:239)

对我来说,就像一个魅力

element(by.cssContainingText('option', 'BeaverBox Testing')).click();

希望它有所帮助。

答案 1 :(得分:78)

我遇到了类似的问题,并最终编写了一个帮助函数来选择下拉值。

我最终决定通过选项号选择我很好,因此写了一个方法,它接受一个元素和optionNumber,并选择那个optionNumber。如果optionNumber为null,则不选择任何内容(不选择下拉列表)。

var selectDropdownbyNum = function ( element, optionNum ) {
  if (optionNum){
    var options = element.all(by.tagName('option'))   
      .then(function(options){
        options[optionNum].click();
      });
  }
};

如果您想要更多详细信息,我写了一篇博文,还包括在下拉列表中验证所选选项的文字:http://technpol.wordpress.com/2013/12/01/protractor-and-dropdowns-validation/

答案 2 :(得分:26)

优雅的方法将涉及制作抽象类似于其他selenium语言绑定提供的开箱即用(例如Python中的Select类或Java)。

让我们创建一个方便的包装器并隐藏实现细节:

var SelectWrapper = function(selector) {
    this.webElement = element(selector);
};
SelectWrapper.prototype.getOptions = function() {
    return this.webElement.all(by.tagName('option'));
};
SelectWrapper.prototype.getSelectedOptions = function() {
    return this.webElement.all(by.css('option[selected="selected"]'));
};
SelectWrapper.prototype.selectByValue = function(value) {
    return this.webElement.all(by.css('option[value="' + value + '"]')).click();
};
SelectWrapper.prototype.selectByPartialText = function(text) {
    return this.webElement.all(by.cssContainingText('option', text)).click();   
};
SelectWrapper.prototype.selectByText = function(text) {
    return this.webElement.all(by.xpath('option[.="' + text + '"]')).click();   
};

module.exports = SelectWrapper;

用法示例(请注意它的可读性和易用性):

var SelectWrapper  = require('select-wrapper');
var mySelect = new SelectWrapper(by.id('locregion'));

# select an option by value
mySelect.selectByValue('4');

# select by visible text
mySelect.selectByText('BoxLox');

解决方案取自以下主题:Select -> option abstraction


仅供参考,创建了一项功能请求:Select -> option abstraction

答案 3 :(得分:20)

element(by.model('parent_id')).sendKeys('BKN01');

答案 4 :(得分:15)

要访问特定选项,您需要提供nth-child()选择器:

ptor.findElement(protractor.By.css('select option:nth-child(1)')).click();

答案 5 :(得分:8)

这就是我做出选择的方式。

function switchType(typeName) {
     $('.dropdown').element(By.cssContainingText('option', typeName)).click();
};

答案 6 :(得分:5)

我是这样做的:

$('select').click();
$('select option=["' + optionInputFromFunction + '"]').click();
// This looks useless but it slows down the click event
// long enough to register a change in Angular.
browser.actions().mouseDown().mouseUp().perform();

答案 7 :(得分:5)

试试这个,它对我有用:

element(by.model('formModel.client'))
    .all(by.tagName('option'))
    .get(120)
    .click();

答案 8 :(得分:4)

你可以试试这个希望它会起作用

element.all(by.id('locregion')).then(function(selectItem) {
  expect(selectItem[0].getText()).toEqual('Ranjans Mobile Testing')
  selectItem[0].click(); //will click on first item
  selectItem[3].click(); //will click on fourth item
});

答案 9 :(得分:3)

我们写了一个库,其中包括3种选择选项的方法:

selectOption(option: ElementFinder |Locator | string, timeout?: number): Promise<void>

selectOptionByIndex(select: ElementFinder | Locator | string, index: number, timeout?: number): Promise<void>

selectOptionByText(select: ElementFinder | Locator | string, text: string, timeout?: number): Promise<void>

此功能的其他功能是,在执行select上的任何操作之前,他们会等待显示元素。

你可以在npm @hetznercloud/protractor-test-helper找到它。 还提供了TypeScript的类型。

答案 10 :(得分:3)

设置选项元素的另一种方法:

<table>
  <thead>...</thead>
  <tfoot>
    <tr>
      <td colspan="7">
        <button class="small">&#60;</button>
        <button class="primary small">1</button>
        <button class="small">2</button>
        <button class="small">3</button>
        <button class="small">4</button>
        <button class="small">&#62;</button>
      </td>
    </tr>
  </tfoot>
  <tbody>...</tbody>
</table>

答案 11 :(得分:2)

选择具有唯一ID的项目(选项),如下所示:

<select
    ng-model="foo" 
    ng-options="bar as bar.title for bar in bars track by bar.id">
</select>

我用这个:

element(by.css('[value="' + neededBarId+ '"]')).click();

答案 12 :(得分:2)

如果以上答案都不适合你,试试这个

也适用于 async/await

用于通过文本选择选项

let textOption = "option2"
await element(by.whichever('YOUR_DROPDOWN_SELECTOR'))
  .getWebElement()
  .findElement(by.xpath(`.//option[text()="${textOption}"]`))
  .click();

或按数字

let optionNumber = 2
await element(by.whichever('YOUR_DROPDOWN_SELECTOR'))
  .getWebElement()
  .findElement(by.xpath(`.//option[${optionNumber}]`))
  .click();

当然你可能需要修改子选项的xpath

不要问我为什么,但当我已经失去希望时,这是我可以自动化下拉菜单的唯一方法

答案 13 :(得分:2)

问题是在常规角度选择框上工作的解决方案不适用于使用量角器的Angular Material md-select和md-option。这个是由另一个发布的,但它对我有用,我无法评论他的帖子(只有23个代表点)。另外,我清理了一下,而不是browser.sleep,我使用了browser.waitForAngular();

var doSubscribe = function(e) {

    //stop the browser form submit
    e.preventDefault();

    //grab the form data
    var data = {
        email: $('#email-input').val(),
        referr: $('#referr').val()
    }
    $.post('subscribe.php',data,function(response) {
        //Not sure what your php script is returning 
        //json is good and it should indicate success or failure
        //so lets say you are returning a json object with a success flag
        if(response.success) {
            //use jquery to open the modal
            $('#myModal').modal('show');
        } else {
            //display error message to user
            alert("Error subscribing");
        }
    },'json');
}

答案 14 :(得分:2)

也许不是超级优雅,但效率很高:

function selectOption(modelSelector, index) {
    for (var i=0; i<index; i++){
        element(by.model(modelSelector)).sendKeys("\uE015");
    }
}

这只是在你想要的选择上发送键,在我们的例子中,我们使用的是modelSelector,但显然你可以使用任何其他选择器。

然后在我的页面对象模型中:

selectMyOption: function (optionNum) {
       selectOption('myOption', optionNum)
}

从测试开始:

myPage.selectMyOption(1);

答案 15 :(得分:1)

在Firefox中选择Droogans's hack修正我明确要提及的选项存在一个问题,希望它可以为某人节省一些麻烦:https://github.com/angular/protractor/issues/480

即使您的测试通过Firefox本地传递,您可能会发现他们在CircleCI或TravisCI上失败,或者您正在使用CI和部署的任何内容。从一开始就意识到这个问题会给我节省很多时间:)

答案 16 :(得分:1)

帮助器设置选项元素:

selectDropDownByText:function(optionValue) {
            element(by.cssContainingText('option', optionValue)).click(); //optionValue: dropDownOption
        }

答案 17 :(得分:1)

如果下面是给定的下拉列表 -

            <select ng-model="operator">
            <option value="name">Addition</option>
            <option value="age">Division</option>
            </select>

然后protractorjs代码可以是 -

        var operators=element(by.model('operator'));
    		operators.$('[value=Addition]').click();

源 - https://github.com/angular/protractor/issues/600

答案 18 :(得分:1)

按索引选择选项:

var selectDropdownElement= element(by.id('select-dropdown'));
selectDropdownElement.all(by.tagName('option'))
      .then(function (options) {
          options[0].click();
      });

答案 19 :(得分:0)

这是一个简单的单行答案,其中angular具有特殊的定位器,可以帮助您从列表中选择索引。

element.all(by.options('o.id as o.name for o in organizations')).get(Index).click()

答案 20 :(得分:0)

以下示例是最简单的方法。我已经测试并通过了量角器版本5.4.2

//Drop down selection  using option's visibility text 

 element(by.model('currency')).element(by.css("[value='Dollar']")).click();
 Or use this, it   $ isshort form for  .By.css
  element(by.model('currency')).$('[value="Dollar"]').click();

//To select using index

var select = element(by.id('userSelect'));
select.$('[value="1"]').click(); // To select using the index .$ means a shortcut to .By.css

完整代码

describe('Protractor Demo App', function() {

  it('should have a title', function() {

     browser.driver.get('http://www.way2automation.com/angularjs-protractor/banking/#/');
    expect(browser.getTitle()).toEqual('Protractor practice website - Banking App');
    element(by.buttonText('Bank Manager Login')).click();
    element(by.buttonText('Open Account')).click();

    //Drop down selection  using option's visibility text 
  element(by.model('currency')).element(by.css("[value='Dollar']")).click();

    //This is a short form. $ in short form for  .By.css
    // element(by.model('currency')).$('[value="Dollar"]').click();

    //To select using index
    var select = element(by.id('userSelect'));
    select.$('[value="1"]').click(); // To select using the index .$ means a shortcut to .By.css
    element(by.buttonText("Process")).click();
    browser.sleep(7500);// wait in miliseconds
    browser.switchTo().alert().accept();

  });
});

答案 21 :(得分:0)

我们可以为此创建一个自定义的DropDown类,并添加以下方法:

async selectSingleValue(value: string) {
        await this.element.element(by.xpath('.//option[normalize-space(.)=\'' + value + '\']')).click();
    }

此外,要验证当前选择的值,我们可以提供:

async getSelectedValues() {
        return await this.element.$('option:checked').getText();
    }

答案 22 :(得分:0)

static selectDropdownValue(dropDownLocator,dropDownListLocator,dropDownValue){
    let ListVal ='';
    WebLibraryUtils.getElement('xpath',dropDownLocator).click()
      WebLibraryUtils.getElements('xpath',dropDownListLocator).then(function(selectItem){
        if(selectItem.length>0)
        {
            for( let i =0;i<=selectItem.length;i++)
               {
                   if(selectItem[i]==dropDownValue)
                   {
                       console.log(selectItem[i])
                       selectItem[i].click();
                   }
               }            
        }

    })

}

答案 23 :(得分:0)

以下是通过选项值或索引进行操作的方法。这个例子有点粗糙,但是它展示了如何做你想做的事情:

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

function selectOptionByOptionIndex(selectFormFieldElementId, index) {

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

        const optionId = optionIds[index];
        const option = element(by.id(optionId));
        option.click();
      });
  });
}

selectOptionByOptionValue('your-id', '1'); //selects first option
selectOptionByOptionIndex('your-id', 1); //selects second option

答案 24 :(得分:0)

这适用于角材料

element(by.css("mat-select[formcontrolname=myMatSelect]")).sendKeys(valueToSet);

如果您的选项中不存在“valueToSet”,则不应设置它。

答案 25 :(得分:0)

我已经改进了PaulL编写的解决方案。 首先,我修改了代码以与最后一个Protractor API兼容。然后我在&#39; onPrepare&#39;中声明了这个功能。 Protractor配置文件的一部分作为浏览器实例的成员,因此可以从任何e2e规范中引用它。

  onPrepare: function() {
    browser._selectDropdownbyNum = function (element, optionNum) {
      /* A helper function to select in a dropdown control an option
      * with specified number.
      */
      return element.all(by.tagName('option')).then(
        function(options) {
          options[optionNum].click();
        });
    };
  },

答案 26 :(得分:0)

您可以按值选择下拉选项: $('#locregion').$('[value="1"]').click();

答案 27 :(得分:0)

我一直在网上搜索关于如何在模型下拉列表中选择一个选项的答案,我已经使用了这个组合,它帮助我使用Angular材料。

元素(by.model(“ModelName”))。click()。element(By.xpath('xpath location'))。click();

似乎在将代码全部放入一行时,它可以在下拉列表中找到该元素。

花了很多时间来解决这个问题,我希望这可以帮助别人。

答案 28 :(得分:0)

Access-Control-Allow-Origin

答案 29 :(得分:0)

设置选项元素的另一种方法:

var setOption = function(optionToSelect) {

    var select = element(by.id('locregion'));
    select.click();
    select.all(by.tagName('option')).filter(function(elem, index) {
        return elem.getText().then(function(text) {
            return text === optionToSelect;
        });
    }).then(function(filteredElements){
        filteredElements[0].click();
    });
};

// using the function
setOption('BeaverBox Testing');

答案 30 :(得分:0)

我们希望使用angularjs材料在那里使用优雅的解决方案,但它没有用,因为在点击md-select之前,DOM中实际上没有选项/ md-option标签。因此,“优雅”的方式对我们不起作用(注意有角度的材料!)这是我们为它做的事情,不知道它是否是最好的方式,但它现在肯定在工作

element.all(by.css('md-select')).each(function (eachElement, index) {
    eachElement.click();                    // select the <select>
    browser.driver.sleep(500);              // wait for the renderings to take effect
    element(by.css('md-option')).click();   // select the first md-option
    browser.driver.sleep(500);              // wait for the renderings to take effect
});

我们需要选择4个选项,当选择打开时,选择下一个选择的方式有一个叠加。这就是为什么我们需要等待500毫秒以确保我们不会遇到物质效应仍然存在的问题。

答案 31 :(得分:-1)

您可以选择以下下拉选项:

ContactCardViewModel

答案 32 :(得分:-1)

按CSS属性

选择选项
element(by.model("organization.parent_id")).element(by.css("[value='1']")).click();

element(by.css("#locregion")).element(by.css("[value='1']")).click();

其中locregion(id),organization.parent_id(模型名称)是select元素的属性。