IT

드롭 다운 protractorjs e2e 테스트에서 옵션을 선택하는 방법

lottoking 2020. 7. 28. 07:44
반응형

드롭 다운 protractorjs 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.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 기능 [ {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, applicationCacheEnabled = false, takesScreenshot = true}]

누구 든지이 문제를 해결하도록 도와 주거나 내가 여기서 잘못하고있는 것에 대해 조명을 줄 수 있고?


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

나는 결국 옵션 번호로 잘 선택하기로 결정 때문에 요소와 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/


나를 위해 매력처럼 일했다

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

도움이 되길 바랍니다.


우아한 접근 방식다른 셀레늄 언어 바인딩이 기본적으로 제공하는 것과 같은 추상화를 만드는 것입니다 (예 : SelectPython 또는 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');

다음 주제에서 해결책을 선택하십시오 .-> 추상화를 선택하십시오 .


참고로, 기능 요청을 작성했습니다 .-> 옵션 추상화를 선택하십시오 .


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

특정 옵션에 액세스하려는 n 번째-하위 () 선택기를 제공해야합니다.

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

옵션을 선택하는 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");
    }
}

이 경우 원하는 선택에 키를 보냅니다.이 경우 modelSelector를 사용하고 선택할 수도 있습니다.

그런 다음 내 페이지 객체 모델에서

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

그리고 테스트에서 :

myPage.selectMyOption(1);

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

문제는 일반 각도 선택 상자에서 작동하는 솔루션이 각도기를 사용하여 각도 재료 md-select 및 md-option에서 작동하지 않는다는 것입니다. 이 게시물은 다른 사람에 의해 게시 게시 저에게 아직 게시물에 댓글을 달 수 없습니다 (23 포인트 만). 또한 browser.sleep 대신 약간 정리했습니다. browser.waitForAngular ();

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

Firefox에서 옵션을 선택하는 데 문제가 있습니다. Droogans의 해킹 은 누군가 명시하고 싶습니다. https://github.com/angular/protractor/issues/480 .

테스트가 Firefox에서 로컬로 전달되는 경우에도 CircleCI 또는 TravisCI 또는 CI 및 배포에 사용중인 모든 테스트에서 실패한 것을 알 수 있습니다. 처음 부터이 문제를 알고 있으면 많은 시간을 절약 할 수 있습니다.)


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

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와 호환 코드를 수정했습니다. 그런 다음 Protractor 구성 파일의 'onPrepare'섹션에 함수를 브라우저 인스턴스 의 멤버로 선언 할 때 모든 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();
        });
    };
  },

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


});

모델 드롭 다운에서 옵션을 선택하는 방법에 대한 답변을 얻기 위해 그물을 트롤링 해 왔으며 Angular 재질을 사용하는 데 도움이되는이 조합을 사용했습니다.

element (by.model ( "ModelName")). click (). element (By.xpath ( 'xpath location')). ​​click ();

코드를 한 줄에 모두 던지면 드롭 다운에서 요소를 찾을 수 있습니다.

이 솔루션에 많은 시간이 걸렸습니다. 이것이 누군가를 도울 수 있기를 바랍니다.


값별로 드롭 다운 옵션을 선택할 수 있습니다. $('#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();
                   }
               }            
        }

    })

}

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 (모델 이름)는 선택 요소의 속성입니다.


다음과 같은 드롭 다운 옵션을 선택할 수 있습니다.

element(by.xpath(
'//*[@id="locregion"]//option[contains(text(),"Ranjans Mobile Testing")]'
)).click();

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

반응형