我正在使用 Protractor 和 cucumber 框架;如何跳出 .filter 或 .map 循环?如果找到匹配项,我不想继续进一步迭代!
Page.prototype.getElementByKey = function (key) {
var foundElement = null;
return someElement.all(by.css('.someClass')).map(function (rawItem, index) {
var itemObject = new ItemObjectClass(rawItem);
return itemObject.getItemKey().then(function (foundItemKey) {
var matched = String(foundItemKey).trim() === String(key).trim();
console.log(' Matched: { ' + matched + ' } index {'+index+'}');
//if we have a match break out of the .filter function
if (matched) {
foundElement = itemObject;
throw new Error("Just our way of breaking out of .filter() above");
}
});
}).then(function () {
//callback
throw new Error('\n!!!!!Callback should not be called;
this means that we could not find an element that matched the passed in key above');
}, function (error) {
//error
console.log('\n*******************errorCallback was called; '+error);
return foundElement;
});
};
上面的代码找到了元素,但继续迭代直到结束,而不是在有匹配项时停止并通过调用 errorCallback 函数中断。
考虑到 .map 函数返回“解析为 map 函数返回的值数组的 promise ”http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.map ,我正在利用这样一个事实,即如果 promise 无法解决, promise 将调用其 errCallback。
通过抛出一个假错误,应该调用 errorCallback 从而跳出 .map 循环。
不幸的是,它成功抛出错误但继续循环而不是中断。我知道,因为当我
console.log("boolean "+matched+" and index "+index);
我明白了:
matched: false index: 0
matched: false index: 1
matched: true index 2 //it should have stopped here since matched = true
matched false index 3 // this should NOT have printed
那么爆发是行不通的吗?
最佳答案
您返回的是单个元素,因此 .reduce
会更可取。
这是一个返回文本为“mylink”的第一个链接的用法示例:
var link = element.all(by.css('a')).reduce(function (result, elem, index) {
if(result) return result;
return elem.getText().then(function(text){
if(text === "mylink") return elem;
});
}).then(function(result){
if(!result) throw new Error("Element not found");
return result;
});
关于selenium - 打破 Protractor .filter() 或 .map() 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38777577/