programing

드롭 다운 프로젝터js e2e 테스트에서 옵션을 선택하는 방법

newnotes 2023. 3. 11. 09:27
반응형

드롭 다운 프로젝터js e2e 테스트에서 옵션을 선택하는 방법

나는 각도 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: '1.65' 드라이버 정보:06.

나도 시도해봤어:

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', '86'2201c45c63f 드라이버 정보: org.openqa.selenium.파이어폭스Firefox 드라이버 기능 [{platform=]MAC, acceptSslCerts=true, javascriptEnabled=true, browserName=false, locationContextEnabled=true, 버전=24.0, cssSelectorsEnabled=true, databaseEnabled=true, 핸들경고=true, browserConnectionEnabled=true, nativeEvents=false, webStorageEnabled=true, applicationCacheEnabled=false, takesScreenshot=true}

누가 이 문제를 해결하도록 도와주거나 내가 여기서 뭘 잘못하고 있는지 설명해 줄 수 있나요?

나는 마법처럼 일했다.

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

저도 같은 문제가 있어서 결국 드롭다운 값을 선택하는 도우미 함수를 작성했습니다.

결국 옵션 번호로 선택하는 것이 좋다고 판단하고 요소와 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/

우아한 접근법은 다른 셀레늄 언어 바인딩이 바로 사용할 수 있는 것과 유사한 추상화를 만드는 것을 포함한다(예:SelectPython Java (Python 자바) 。

편리한 래퍼를 만들고 구현 세부 정보를 안에 숨깁니다.

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

다음 토픽에서 얻은 솔루션:-> 옵션 추상화를 선택합니다.


참고: 기능 요청을 작성했습니다.-> 옵션 추상화를 선택합니다.

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

특정 옵션에 액세스하려면 n번째-child() 셀렉터를 지정해야 합니다.

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

이게 내가 선택한 방법이야

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

방법은 다음과 같습니다.

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

시험해 보세요.제게는 효과가 있어요.

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

잘 되길 바라면서 해봐

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

옵션 요소를 설정하는 다른 방법은 다음과 같습니다.

var select = element(by.model('organization.parent_id'));
select.$('[value="1"]').click();

다음과 같이 고유한 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();

옵션을 선택하는 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 의 타이핑도 준비되어 있습니다.

매우 우아하지는 않지만 효율적입니다.

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

그러면 원하는 선택으로 키가 전송됩니다.이 경우 model Selector를 사용하고 있지만 다른 선택기를 사용할 수 있습니다.

그런 다음 내 페이지 개체 모델에서 다음을 수행합니다.

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

테스트 결과:

myPage.selectMyOption(1);

문제는 일반 각도 선택 상자에서 작동하는 솔루션이 각도 재료 md-select 및 각도기를 사용하는 md-option과 함께 작동하지 않는다는 것입니다.이것은 다른 사람이 올린 것입니다만, 나에게는 효과가 있어, 아직 코멘트를 할 수 없습니다(점수 23점).그리고 브라우저 대신 조금 정리했어요.sleep, 브라우저를 사용했어요.wait For Angular();

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

파이어폭스에서는, Droogans의 해킹에 의해서 수정되는 옵션을 선택하는 것에 문제가 있습니다.이것에 의해서, 누군가가 수고를 덜 수 있을 것으로 기대하고 있습니다.https://github.com/angular/protractor/issues/480

Firefox를 사용하여 로컬로 테스트를 통과하더라도 CircleCI 또는 TravisCI 또는 CI&Deployment에 사용하는 모든 테스트에서 테스트가 실패할 수 있습니다.처음부터 이 문제를 알고 있으면 많은 시간을 절약할 수 있었을 것입니다.

옵션 요소를 설정하는 도우미:

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

아래가 지정된 드롭다운인 경우-

            <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

색인별 옵션 선택:

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

PaulL이 작성한 솔루션을 조금 개선했습니다.우선 지난번 Protractor API와 호환되도록 코드를 수정했습니다.그런 다음 임의의 e2e 사양에서 참조할 수 있도록 Protractor 구성 파일의 'onPrepare' 섹션에서 함수를 선언합니다.

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

하다는 Version Protractor Version에서 했습니다.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();

  });
});

모델 드롭다운에서 옵션을 선택하는 방법에 대한 답변을 얻기 위해 인터넷을 뒤지고 있으며, 이 조합을 사용해 Angular material을 사용하는 데 도움이 되었습니다.

element(by.model("ModelName")).click().element(By.xpath('xpathlocation')).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();

물론 자녀 옵션의 xpath를 수정해야 할 수도 있습니다.

이유를 묻지 마세요. 하지만 이미 희망을 잃었을 때 드롭다운을 자동화할 수 있는 유일한 방법은 이것뿐입니다.


갱신하다

실제로 이 접근법조차 효과가 없는 경우가 한 번 있었습니다.이 일은 좀 못생겼지만 효과가 있었다.을 선택해야 했습니다.

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개의 선택을 해야 했고, 선택이 열려 있는 동안 다음 선택을 선택하는 데 방해가 되는 오버레이가 있습니다.그래서 우리는 500ms를 기다려야 합니다. 재료 효과가 아직 작동 중이어서 문제가 생기지 않도록 하기 위해서입니다.

옵션 요소를 설정하는 다른 방법은 다음과 같습니다.

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');
----------
element.all(by.id('locregion')).then(function(Item)
{
 // Item[x] = > // x is [0,1,2,3]element you want to click
  Item[0].click(); //first item

  Item[3].click();     // fourth item
  expect(Item[0].getText()).toEqual('Ranjans Mobile Testing')


});

로 드롭다운할 수 .$('#locregion').$('[value="1"]').click();

다음은 옵션또는 인덱스로 수행하는 방법입니다.이 예에서는 다소 조잡하지만 원하는 작업을 수행하는 방법을 보여 줍니다.

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

    })

}

이를 위한 커스텀 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();
    }

이것은 angular에 리스트에서 선택 및 인덱스에 도움이 되는 특별한 로케이터가 있는 단순한 한 줄의 대답입니다.

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

언급URL : https://stackoverflow.com/questions/19599450/how-to-select-option-in-drop-down-protractorjs-e2e-tests

반응형