Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在下拉式量角器JS e2e测试中选择选项_Javascript_Angularjs_Selenium_Testing_Protractor - Fatal编程技术网

Javascript 如何在下拉式量角器JS e2e测试中选择选项

Javascript 如何在下拉式量角器JS e2e测试中选择选项,javascript,angularjs,selenium,testing,protractor,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-mod

我试图从下拉列表中选择一个选项,用于使用量角器进行角度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>
这给了我以下错误:

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

我也尝试过:

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:'macosx',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 功能[{platform=MAC,acceptSslCerts=true,javascriptEnabled=true,browserName=firefox,rotatable=false,locationContextEnabled=true,version=24.0,cssSelectorsEnabled=true,databaseEnabled=true,handlesAlerts=true,browserConnectionEnabled=true,nativeEvents=false,webStorageEnabled=true,applicationCacheAbled=false,takesScreenshot=true}]


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

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

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

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

我最终决定我可以通过optionNumber进行选择,因此编写了一个方法,该方法接受一个元素和optionNumber,并选择optionNumber。如果optionNumber为空,则不选择任何内容(使下拉列表未选中)


我写了一篇博客文章,如果你想了解更多细节,它还包括在下拉列表中验证所选选项的文本:

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

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

也许不是非常优雅,但效率很高:

function selectOption(modelSelector, index) {
    for (var i=0; i<index; i++){
        element(by.model(modelSelector)).sendKeys("\uE015");
    }
}
从测试中可以看出:

myPage.selectMyOption(1);
我是这样做的:

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

我就是这样选择的

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

对我来说,这工作很有魅力

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

我们想用angularjs材质使用优雅的解决方案,但它不起作用,因为在单击md select之前,DOM中实际上没有option/md选项标记。所以“优雅”的方式对我们不起作用(注意棱角材料!)这里是我们为它所做的,不知道这是否是最好的方式,但它现在确实起作用了

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
});
element.all(by.css('md-select')).each(函数(每个元素,索引){
eachElement.click();//选择
browser.driver.sleep(500);//等待渲染生效
元素(by.css('md-option'))。单击();//选择第一个md选项
browser.driver.sleep(500);//等待渲染生效
});

我们需要选择4个选择,当选择打开时,在选择下一个选择时会有一个覆盖。这就是为什么我们需要等待500毫秒,以确保我们不会因为物质效应仍在起作用而陷入麻烦

一种优雅的方法需要制作一个类似于其他selenium语言绑定提供的开箱即用的抽象(例如Python或Java中的
Select
类)

让我们制作一个方便的包装器,并将实现细节隐藏在其中:

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;
用法示例(注意它的可读性和易用性):

从以下主题获取的解决方案:



仅供参考,创建了一个功能请求:。

试试这个,它对我有用:

element(by.model('formModel.client'))
    .all(by.tagName('option'))
    .get(120)
    .click();
要选择具有唯一ID的项目(选项),如此处所示:

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

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

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');
var select = element(by.model('organization.parent_id'));
select.$('[value="1"]').click();
selectDropDownByText:function(optionValue) {
            element(by.cssContainingText('option', optionValue)).click(); //optionValue: dropDownOption
        }

在Firefox中选择选项有一个问题,我想在这里明确提到,希望它能为某些人省去一些麻烦:


即使您的测试通过了Firefox的本地测试,您也可能会发现它们在CircleCI或TravisCI或您用于CI&deployment的任何东西上失败。从一开始就意识到这个问题会节省我很多时间:)

问题是,在常规角度选择框上工作的解决方案不适用于使用量角器的角度材质md select和md选项。这篇文章是由另一位发表的,但它对我有效,我还无法对他的文章发表评论(只有23个代表点)。另外,我对它进行了一些清理,而不是使用browser.sleep,我使用了browser.waitForAngular()

element.all(by.css('md-select')).each(函数(每个元素,索引){
eachElement.click();//选择
browser.waitForAngular();//等待渲染生效
元素(by.css('md-option'))。单击();//选择第一个md选项
browser.waitForAngular();//等待渲染生效
});

我一直在网上搜寻关于如何在模型下拉列表中选择选项的答案,我使用了这个组合,它帮助我解决了角度材料的问题

element(by.model("ModelName")).click().element(By.xpath('xpathlocation')).click();
似乎在一行中抛出所有代码时,它可以在下拉列表中找到元素


此解决方案花费了大量时间,我希望这能帮助他人解决问题。

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

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');
var select = element(by.model('organization.parent_id'));
select.$('[value="1"]').click();
selectDropDownByText:function(optionValue) {
            element(by.cssContainingText('option', optionValue)).click(); //optionValue: dropDownOption
        }

您可以按值选择下拉选项:
$('#locregion').$('[value=“1”]')。单击()

帮助程序以设置选项元素:

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');
var select = element(by.model('organization.parent_id'));
select.$('[value="1"]').click();
selectDropDownByText:function(optionValue) {
            element(by.cssContainingText('option', optionValue)).click(); //optionValue: dropDownOption
        }

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


附加
分部

按索引选择选项:

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

我改进了PaulL编写的解决方案。 首先,我修复了与最后一个量角器API兼容的代码。然后我将量角器配置文件的“onPrepare”部分中的函数声明为浏览器实例的成员
selectDropDownByText:function(optionValue) {
            element(by.cssContainingText('option', optionValue)).click(); //optionValue: dropDownOption
        }
var selectDropdownElement= element(by.id('select-dropdown'));
selectDropdownElement.all(by.tagName('option'))
      .then(function (options) {
          options[0].click();
      });
  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();
        });
    };
  },
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>
<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>
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
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();
                   }
               }            
        }

    })

}
async selectSingleValue(value: string) {
        await this.element.element(by.xpath('.//option[normalize-space(.)=\'' + value + '\']')).click();
    }
async getSelectedValues() {
        return await this.element.$('option:checked').getText();
    }
//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();

  });
});
element.all(by.options('o.id as o.name for o in organizations')).get(Index).click()
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();