我进去并为每个下拉菜单创建了 id 标签。我尝试创建一个循环来选择下拉列表中的每个制造商,而不必编写 300 多行代码,因为某些下拉列表中有很多选项。我尝试过,但找不到办法。例如,第二个下拉菜单是“source_manufacturer”。
这是我尝试过的:
var expected = ['COMFORT-AIRE', 'Daewoo', 'GE'];
var els = element.all(by.id('source_manufacturer'));
for (var i = 0; i < expected.length; ++i) {
expect(els.get(i).getText()).toEqual(expected[i]);
}
这是html代码:
<select id="source_manufacturer" ng-class="{'btn btn-default' : !$root.isMobile.iOS()}" class="form-control ng-valid btn btn-default ng-not-empty ng-touched ng-dirty ng-valid-parse" ng-model="manufacturer" ng-options="m.name for m in manufacturers">
`<option selected="selected" value="object:439" label="COMFORT-AIRE">COMFORT-AIRE</option>
....
<option value="object:443" label="Whirlpool">Whirlpool</option></select>`
这是错误消息:失败:索引超出范围。尝试访问索引为 1 处的元素,但只有 1 个元素与 locator By(css 选择器,*[id="source_manufacturer"]) 匹配。我想测试是否每一项都可以被选择并且它实际上会发生变化。
预期显示列表中的每个元素,而不是单个元素。
这就是我单击列表中每个单独元素的方式:
element(by.id('source_manufacturer')).click().
element(by.cssContainingText('option', 'GE')).click();
最佳答案
首先,您应该确保确实有多个带有 source_manufacturer
id 的 select
元素。那么,您应该使用 each()
而不是常规的 for 循环。而且,我会在建议的选择选项结构上使用优雅的抽象 here :
var expected = ['COMFORT-AIRE', 'Daewoo', 'GE']
var selects = element.all(by.id('source_manufacturer'));
selects.each(function (select, index) {
var selectWrapper = SelectWrapper(select);
selectWrapper.selectByPartialText(expected[index]);
expect(selectWrapper.getSelectedOptions().first().getText()).toEqual(expected[index]);
});
关于javascript - 循环将选择下拉列表中的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38707283/