量角器函数错误生成随机选项Selectui

时间:2017-04-20 15:35:53

标签: javascript jquery selenium protractor

  <tr class="form-row form-row-odd form-row-err  form-cols-2 form_element_company_id">
    <th>Company&nbsp;
        <span class="required">*</span>
    </th>
    <td>
        <select name="company_id" class="selectmenu input-inf select2-initialized select2-hidden-accessible" tabindex="-1" aria-hidden="true">
            <option value="">— None —</option>
            <option value="1" class="sub-option-0 ">Option 1</option>
            <option value="14" class="sub-option-0 ">Option 2</option>
            <option value="45" class="sub-option-1 " data-parent-name="Option 2="14">Option 2-1</option>
            <option value="46" class="sub-option-1 " data-parent-name="Option 2" data-parent-id="14">Option 2-2</option>
            <option value="47" class="sub-option-1 " data-parent-name="Option 2" data-parent-id="14">Option 2-3</option>
            <option value="29" class="sub-option-0 ">Option 3</option>
            <option value="30" class="sub-option-0 ">Option 4</option>
            <option value="31" class="sub-option-0 ">Option 5</option>
        </select>
    </td>
</tr>

我试图创建一个自动从select2 name =&#34; company_id&#34;中选择一个选项的函数。 : 到目前为止,我已经尝试过:

   function setUserCompany('selector'){    
    var companyField = $('selector');
        if (companyField.length == 0) { 
        return; 
        }
        var options = companyField.find('option')
    if (options.length == 0) {
    return; 
    }
    var randomIdx = Math.floor((Math.random() * selector.length)+1);
    var randomValue = $(options.get(randomIdx)).attr('value');
    companyField.select2().val(randomValue).trigger('change'); 
    }

^让我&#34;失败:companyField.find不是一个函数&#34;。

// var allOptions = element(by.css('name="group_id"')).element(by.css('.selectmenu')).all(by.tagName('option'));
    // allOptions.count().then(function(numberOfItems) {
    // return Math.floor(Math.random() * numberOfItems) + 1;
    // }).then(function(randomNumber) {
    // allOptions.get(randomNumber).click();
    // randomNumber();
    // });

^似乎无法正常工作

1 个答案:

答案 0 :(得分:1)

我认为你想获得随机值或点击随机选项。你几乎完全错过了通过css名称获取选择框。试试这个,

var companySelectBox = browser.element(by.css('[name="company_id"]'));
companySelectBox.all(by.tagName('option')).then(function(options){
    //random id between option length
    var randomId = Math.floor((Math.random() * options.length)+1);
    console.log('random id ' + randomId); 
    options[randomId].getText().then(function(text){
        console.log('random option text ' + text); 
    });
    //click on random option  
    options[randomId].click();
    //TODO: whatever other task similar 
});